@codelia/runtime 0.1.26 → 0.1.28

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.js CHANGED
@@ -3423,7 +3423,7 @@ var createEditTool = (sandboxKey) => defineTool4({
3423
3423
  const sandbox = await getSandboxContext(ctx, sandboxKey);
3424
3424
  resolved = sandbox.resolvePath(input.file_path);
3425
3425
  } catch (error) {
3426
- return `Security error: ${String(error)}`;
3426
+ throw new Error(`Security error: ${String(error)}`);
3427
3427
  }
3428
3428
  if (input.old_string !== "" && input.old_string === input.new_string) {
3429
3429
  return {
@@ -3442,22 +3442,24 @@ var createEditTool = (sandboxKey) => defineTool4({
3442
3442
  try {
3443
3443
  const stat = await fs7.stat(resolved);
3444
3444
  if (stat.isDirectory()) {
3445
- return `Path is a directory: ${input.file_path}`;
3445
+ throw new Error(`Path is a directory: ${input.file_path}`);
3446
3446
  }
3447
3447
  fileExists = true;
3448
3448
  content = await fs7.readFile(resolved, "utf8");
3449
3449
  } catch (_error) {
3450
3450
  if (input.old_string !== "") {
3451
- return `File not found: ${input.file_path}`;
3451
+ throw new Error(`File not found: ${input.file_path}`);
3452
3452
  }
3453
3453
  }
3454
3454
  if (input.expected_hash) {
3455
3455
  if (!fileExists) {
3456
- return `Expected hash provided but file not found: ${input.file_path}`;
3456
+ throw new Error(
3457
+ `Expected hash provided but file not found: ${input.file_path}`
3458
+ );
3457
3459
  }
3458
3460
  const currentHash = hashContent(content);
3459
3461
  if (currentHash !== input.expected_hash) {
3460
- return `Hash mismatch for ${input.file_path}`;
3462
+ throw new Error(`Hash mismatch for ${input.file_path}`);
3461
3463
  }
3462
3464
  }
3463
3465
  let replacements = 0;
@@ -3473,12 +3475,14 @@ var createEditTool = (sandboxKey) => defineTool4({
3473
3475
  matchMode
3474
3476
  );
3475
3477
  if (!matchResult || matchResult.matches.length === 0) {
3476
- return `String not found in ${input.file_path}`;
3478
+ throw new Error(`String not found in ${input.file_path}`);
3477
3479
  }
3478
3480
  modeUsed = matchResult.mode;
3479
3481
  let matches = matchResult.matches;
3480
3482
  if (!replaceAll && matches.length > 1) {
3481
- return `Multiple matches (${matches.length}) found in ${input.file_path}`;
3483
+ throw new Error(
3484
+ `Multiple matches (${matches.length}) found in ${input.file_path}`
3485
+ );
3482
3486
  }
3483
3487
  if (!replaceAll) {
3484
3488
  matches = [matches[0]];
@@ -3487,7 +3491,9 @@ var createEditTool = (sandboxKey) => defineTool4({
3487
3491
  nextContent = applyReplacements(content, matches, input.new_string);
3488
3492
  }
3489
3493
  if (input.expected_replacements !== void 0 && replacements !== input.expected_replacements) {
3490
- return `Expected ${input.expected_replacements} replacements, found ${replacements}`;
3494
+ throw new Error(
3495
+ `Expected ${input.expected_replacements} replacements, found ${replacements}`
3496
+ );
3491
3497
  }
3492
3498
  const diff = createUnifiedDiff(input.file_path, content, nextContent);
3493
3499
  if (dryRun) {
@@ -3512,7 +3518,7 @@ var createEditTool = (sandboxKey) => defineTool4({
3512
3518
  await fs7.mkdir(path8.dirname(resolved), { recursive: true });
3513
3519
  await fs7.writeFile(resolved, nextContent, "utf8");
3514
3520
  } catch (error) {
3515
- return `Error editing file: ${String(error)}`;
3521
+ throw new Error(`Error editing file: ${String(error)}`);
3516
3522
  }
3517
3523
  return {
3518
3524
  summary: `Replaced ${replacements} occurrence(s) in ${input.file_path}`,
@@ -4726,49 +4732,339 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
4726
4732
  import { defineTool as defineTool12 } from "@codelia/core";
4727
4733
  import { z as z13 } from "zod";
4728
4734
 
4735
+ // src/tools/session-context.ts
4736
+ var createToolSessionContextKey = (getSessionId) => ({
4737
+ id: "tool-session-context",
4738
+ create: () => {
4739
+ const sessionId = getSessionId()?.trim() || null;
4740
+ return { sessionId };
4741
+ }
4742
+ });
4743
+ var getToolSessionContext = async (ctx, key) => ctx.resolve(key);
4744
+
4729
4745
  // src/tools/todo-store.ts
4746
+ var TODO_SESSION_META_KEY = "codelia_todos";
4747
+ var DEFAULT_TODO_PRIORITY = 3;
4748
+ var normalizeOptionalText = (value) => {
4749
+ if (typeof value !== "string") return void 0;
4750
+ const trimmed = value.trim();
4751
+ return trimmed.length ? trimmed : void 0;
4752
+ };
4753
+ var isTodoStatus = (value) => value === "pending" || value === "in_progress" || value === "completed";
4754
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4755
+ var normalizeTodoIdBase = (value) => {
4756
+ const trimmed = value.trim().toLowerCase();
4757
+ const withHyphen = trimmed.replace(/\s+/g, "-");
4758
+ const safe = withHyphen.replace(/[^a-z0-9._-]+/g, "-");
4759
+ const compact = safe.replace(/-+/g, "-");
4760
+ const stripped = compact.replace(/^[-_.]+|[-_.]+$/g, "");
4761
+ return stripped.length ? stripped : "todo";
4762
+ };
4763
+ var slugFromContent = (content) => {
4764
+ const source = normalizeOptionalText(content) ?? "todo";
4765
+ return normalizeTodoIdBase(source);
4766
+ };
4767
+ var toTodoPriority = (value) => {
4768
+ const numericValue = typeof value === "number" ? value : Number.NaN;
4769
+ if (!Number.isInteger(numericValue)) return DEFAULT_TODO_PRIORITY;
4770
+ if (numericValue <= 1) return 1;
4771
+ if (numericValue >= 5) return 5;
4772
+ return numericValue;
4773
+ };
4774
+ var toUniqueId = (baseId, usedIds) => {
4775
+ let candidate = baseId;
4776
+ let suffix = 2;
4777
+ while (usedIds.has(candidate)) {
4778
+ candidate = `${baseId}-${suffix}`;
4779
+ suffix += 1;
4780
+ }
4781
+ usedIds.add(candidate);
4782
+ return candidate;
4783
+ };
4784
+ var normalizeTodoId = (value) => normalizeTodoIdBase(value);
4785
+ var normalizeTodoItems = (todos) => {
4786
+ const usedIds = /* @__PURE__ */ new Set();
4787
+ return todos.map((todo, index) => {
4788
+ const content = normalizeOptionalText(todo.content) ?? `Todo ${index + 1}`;
4789
+ const preferredId = typeof todo.id === "string" && todo.id.trim().length ? normalizeTodoIdBase(todo.id) : slugFromContent(content);
4790
+ return {
4791
+ id: toUniqueId(preferredId, usedIds),
4792
+ content,
4793
+ status: todo.status,
4794
+ priority: toTodoPriority(todo.priority),
4795
+ notes: normalizeOptionalText(todo.notes),
4796
+ activeForm: normalizeOptionalText(todo.activeForm)
4797
+ };
4798
+ });
4799
+ };
4800
+ var setTodosForSession = (sessionId, todos) => {
4801
+ const normalized = normalizeTodoItems(todos);
4802
+ todoStore.set(sessionId, normalized);
4803
+ return normalized;
4804
+ };
4805
+ var getTodosForSession = (sessionId) => normalizeTodoItems(todoStore.get(sessionId) ?? []);
4806
+ var clearTodosForSession = (sessionId) => {
4807
+ todoStore.delete(sessionId);
4808
+ };
4809
+ var readTodosFromSessionMeta = (meta) => {
4810
+ const raw = meta?.[TODO_SESSION_META_KEY];
4811
+ if (!Array.isArray(raw)) return [];
4812
+ const todos = [];
4813
+ for (const entry of raw) {
4814
+ if (!isRecord2(entry)) continue;
4815
+ const status = entry.status;
4816
+ if (!isTodoStatus(status)) continue;
4817
+ const content = typeof entry.content === "string" ? entry.content : "";
4818
+ todos.push({
4819
+ id: typeof entry.id === "string" ? entry.id : void 0,
4820
+ content,
4821
+ status,
4822
+ priority: typeof entry.priority === "number" ? entry.priority : void 0,
4823
+ notes: typeof entry.notes === "string" ? entry.notes : void 0,
4824
+ activeForm: typeof entry.activeForm === "string" ? entry.activeForm : void 0
4825
+ });
4826
+ }
4827
+ return normalizeTodoItems(todos);
4828
+ };
4829
+ var mergeTodosIntoSessionMeta = (meta, todos) => {
4830
+ const nextMeta = meta ? { ...meta } : {};
4831
+ if (todos.length > 0) {
4832
+ nextMeta[TODO_SESSION_META_KEY] = todos.map((todo) => ({ ...todo }));
4833
+ } else {
4834
+ delete nextMeta[TODO_SESSION_META_KEY];
4835
+ }
4836
+ return Object.keys(nextMeta).length > 0 ? nextMeta : void 0;
4837
+ };
4838
+ var countInProgressTodos = (todos) => todos.filter((todo) => todo.status === "in_progress").length;
4839
+ var getTodoStats = (todos) => ({
4840
+ pending: todos.filter((todo) => todo.status === "pending").length,
4841
+ inProgress: todos.filter((todo) => todo.status === "in_progress").length,
4842
+ completed: todos.filter((todo) => todo.status === "completed").length
4843
+ });
4844
+ var statusOrder = {
4845
+ in_progress: 0,
4846
+ pending: 1,
4847
+ completed: 2
4848
+ };
4849
+ var sortTodosForDisplay = (todos) => todos.map((todo, index) => ({ todo, index })).sort((a, b) => {
4850
+ const statusDiff = statusOrder[a.todo.status] - statusOrder[b.todo.status];
4851
+ if (statusDiff !== 0) return statusDiff;
4852
+ const priorityDiff = a.todo.priority - b.todo.priority;
4853
+ if (priorityDiff !== 0) return priorityDiff;
4854
+ return a.index - b.index;
4855
+ }).map((entry) => entry.todo);
4856
+ var pickNextTodo = (todos) => {
4857
+ const inProgress = todos.find((todo) => todo.status === "in_progress");
4858
+ if (inProgress) return inProgress;
4859
+ const pending = sortTodosForDisplay(todos).find(
4860
+ (todo) => todo.status === "pending"
4861
+ );
4862
+ return pending ?? null;
4863
+ };
4730
4864
  var todoStore = /* @__PURE__ */ new Map();
4731
4865
 
4732
4866
  // src/tools/todo-read.ts
4733
- var createTodoReadTool = (sandboxKey) => defineTool12({
4867
+ var statusSymbol = {
4868
+ pending: "[ ]",
4869
+ in_progress: "[>]",
4870
+ completed: "[x]"
4871
+ };
4872
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool12({
4734
4873
  name: "todo_read",
4735
- description: "Read the in-session todo list.",
4874
+ description: "Read the in-session todo plan with execution order and next step.",
4736
4875
  input: z13.object({}),
4737
4876
  execute: async (_input, ctx) => {
4738
4877
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4739
- const todos = todoStore.get(sandbox.sessionId) ?? [];
4878
+ const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
4879
+ const todoSessionId = sessionContext?.sessionId && sessionContext.sessionId.length > 0 ? sessionContext.sessionId : sandbox.sessionId;
4880
+ const todos = getTodosForSession(todoSessionId);
4740
4881
  if (!todos.length) return "Todo list is empty";
4741
- return todos.map((todo, index) => {
4742
- const status = todo.status === "completed" ? "[x]" : todo.status === "in_progress" ? "[>]" : "[ ]";
4743
- return `${index + 1}. ${status} ${todo.content}`;
4744
- }).join("\n");
4882
+ const orderedTodos = sortTodosForDisplay(todos);
4883
+ const lines = ["Todo plan:"];
4884
+ for (const [index, todo] of orderedTodos.entries()) {
4885
+ const label = todo.status === "in_progress" && todo.activeForm ? todo.activeForm : todo.content;
4886
+ lines.push(
4887
+ `${index + 1}. ${statusSymbol[todo.status]} [${todo.id}] (p${todo.priority}) ${label}`
4888
+ );
4889
+ if (todo.notes) {
4890
+ lines.push(` note: ${todo.notes}`);
4891
+ }
4892
+ }
4893
+ const stats = getTodoStats(orderedTodos);
4894
+ const nextTodo = pickNextTodo(orderedTodos);
4895
+ lines.push(
4896
+ `Summary: ${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed`
4897
+ );
4898
+ if (nextTodo) {
4899
+ lines.push(`Next: [${nextTodo.id}] ${nextTodo.content}`);
4900
+ } else {
4901
+ lines.push("Next: none");
4902
+ }
4903
+ const inProgressCount = countInProgressTodos(orderedTodos);
4904
+ if (inProgressCount > 1) {
4905
+ lines.push(
4906
+ `Warning: ${inProgressCount} items are in_progress (expected at most 1).`
4907
+ );
4908
+ }
4909
+ return lines.join("\n");
4745
4910
  }
4746
4911
  });
4747
4912
 
4748
4913
  // src/tools/todo-write.ts
4749
4914
  import { defineTool as defineTool13 } from "@codelia/core";
4750
4915
  import { z as z14 } from "zod";
4751
- var createTodoWriteTool = (sandboxKey) => defineTool13({
4916
+ var todoStatusSchema = z14.enum(["pending", "in_progress", "completed"]);
4917
+ var todoPrioritySchema = z14.number().int().min(1).max(5);
4918
+ var todoItemSchema = z14.object({
4919
+ id: z14.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
4920
+ content: z14.string().min(1).describe("Todo item text."),
4921
+ status: todoStatusSchema.describe("Todo status."),
4922
+ priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
4923
+ notes: z14.string().optional().describe("Optional implementation notes."),
4924
+ activeForm: z14.string().optional().describe("Optional in-progress phrasing for UI display.")
4925
+ });
4926
+ var todoPatchItemSchema = z14.object({
4927
+ id: z14.string().min(1).describe("Target todo ID."),
4928
+ remove: z14.boolean().optional().describe("Set true to remove the todo item."),
4929
+ content: z14.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
4930
+ status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
4931
+ priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
4932
+ notes: z14.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
4933
+ activeForm: z14.string().nullable().default(null).describe("Updated in-progress phrasing (null keeps current, empty clears).")
4934
+ });
4935
+ var todoWriteInputSchema = z14.object({
4936
+ mode: z14.enum(["new", "append", "patch", "clear"]).default("new").describe("Update mode. Default is new."),
4937
+ todos: z14.array(todoItemSchema).default([]).describe("Todo items for new/append mode."),
4938
+ updates: z14.array(todoPatchItemSchema).default([]).describe("Patch operations for patch mode.")
4939
+ }).superRefine((input, ctx) => {
4940
+ if (input.mode === "patch") {
4941
+ if (input.updates.length === 0) {
4942
+ ctx.addIssue({
4943
+ code: z14.ZodIssueCode.custom,
4944
+ path: ["updates"],
4945
+ message: "patch mode requires at least one update item."
4946
+ });
4947
+ }
4948
+ if (input.todos.length > 0) {
4949
+ ctx.addIssue({
4950
+ code: z14.ZodIssueCode.custom,
4951
+ path: ["todos"],
4952
+ message: "patch mode does not accept todos."
4953
+ });
4954
+ }
4955
+ return;
4956
+ }
4957
+ if (input.mode === "clear") {
4958
+ if (input.todos.length > 0) {
4959
+ ctx.addIssue({
4960
+ code: z14.ZodIssueCode.custom,
4961
+ path: ["todos"],
4962
+ message: "clear mode does not accept todos."
4963
+ });
4964
+ }
4965
+ if (input.updates.length > 0) {
4966
+ ctx.addIssue({
4967
+ code: z14.ZodIssueCode.custom,
4968
+ path: ["updates"],
4969
+ message: "clear mode does not accept updates."
4970
+ });
4971
+ }
4972
+ return;
4973
+ }
4974
+ if (input.todos.length === 0) {
4975
+ ctx.addIssue({
4976
+ code: z14.ZodIssueCode.custom,
4977
+ path: ["todos"],
4978
+ message: `${input.mode} mode requires at least one todo item.`
4979
+ });
4980
+ }
4981
+ if (input.updates.length > 0) {
4982
+ ctx.addIssue({
4983
+ code: z14.ZodIssueCode.custom,
4984
+ path: ["updates"],
4985
+ message: `${input.mode} mode does not accept updates.`
4986
+ });
4987
+ }
4988
+ });
4989
+ var loadSessionTodos = (sessionId) => getTodosForSession(sessionId);
4990
+ var formatSuccess = (mode, todos) => {
4991
+ const stats = getTodoStats(todos);
4992
+ const nextTodo = pickNextTodo(todos);
4993
+ const nextHint = nextTodo ? ` Next: [${nextTodo.id}] ${nextTodo.content}.` : " Next: none.";
4994
+ return `Updated todos (${mode}): ${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed.${nextHint}`;
4995
+ };
4996
+ var withPatchApplied = (currentTodos, updates) => {
4997
+ const normalizedUpdates = updates.map((update) => ({
4998
+ ...update,
4999
+ id: normalizeTodoId(update.id)
5000
+ }));
5001
+ const currentIds = new Set(currentTodos.map((todo) => todo.id));
5002
+ const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
5003
+ if (missingIds.length > 0) {
5004
+ return {
5005
+ todos: [...currentTodos],
5006
+ error: `Patch failed: unknown todo id(s): ${Array.from(new Set(missingIds)).join(", ")}`
5007
+ };
5008
+ }
5009
+ let nextInputs = currentTodos.map((todo) => ({ ...todo }));
5010
+ for (const update of normalizedUpdates) {
5011
+ const index = nextInputs.findIndex((todo) => todo.id === update.id);
5012
+ if (index < 0) continue;
5013
+ if (update.remove) {
5014
+ nextInputs = [
5015
+ ...nextInputs.slice(0, index),
5016
+ ...nextInputs.slice(index + 1)
5017
+ ];
5018
+ continue;
5019
+ }
5020
+ const previous = nextInputs[index];
5021
+ nextInputs[index] = {
5022
+ ...previous,
5023
+ content: update.content !== null ? update.content : previous.content,
5024
+ status: update.status !== null ? update.status : previous.status,
5025
+ priority: update.priority !== null ? update.priority : previous.priority,
5026
+ notes: update.notes !== null ? update.notes : previous.notes,
5027
+ activeForm: update.activeForm !== null ? update.activeForm : previous.activeForm
5028
+ };
5029
+ }
5030
+ return { todos: normalizeTodoItems(nextInputs) };
5031
+ };
5032
+ var createTodoWriteTool = (sandboxKey, sessionContextKey) => defineTool13({
4752
5033
  name: "todo_write",
4753
- description: "Replace the in-session todo list.",
4754
- input: z14.object({
4755
- todos: z14.array(
4756
- z14.object({
4757
- content: z14.string().describe("Todo item text."),
4758
- status: z14.enum(["pending", "in_progress", "completed"]).describe("Todo status."),
4759
- activeForm: z14.string().optional().describe("Optional in-progress phrasing for UI display.")
4760
- })
4761
- )
4762
- }),
5034
+ description: "Maintain the in-session todo plan with new, append, patch, or clear updates.",
5035
+ input: todoWriteInputSchema,
4763
5036
  execute: async (input, ctx) => {
4764
5037
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4765
- todoStore.set(sandbox.sessionId, input.todos);
4766
- const stats = {
4767
- pending: input.todos.filter((todo) => todo.status === "pending").length,
4768
- inProgress: input.todos.filter((todo) => todo.status === "in_progress").length,
4769
- completed: input.todos.filter((todo) => todo.status === "completed").length
4770
- };
4771
- return `Updated todos: ${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed`;
5038
+ const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
5039
+ const todoSessionId = sessionContext?.sessionId && sessionContext.sessionId.length > 0 ? sessionContext.sessionId : sandbox.sessionId;
5040
+ const currentTodos = loadSessionTodos(todoSessionId);
5041
+ let mode = input.mode;
5042
+ let nextTodos = [];
5043
+ if (input.mode === "patch") {
5044
+ mode = "patch";
5045
+ const patched = withPatchApplied(currentTodos, input.updates);
5046
+ if (patched.error) return patched.error;
5047
+ nextTodos = patched.todos;
5048
+ } else if (input.mode === "append") {
5049
+ mode = "append";
5050
+ nextTodos = normalizeTodoItems([...currentTodos, ...input.todos]);
5051
+ } else if (input.mode === "clear") {
5052
+ mode = "clear";
5053
+ nextTodos = [];
5054
+ } else {
5055
+ mode = "new";
5056
+ nextTodos = normalizeTodoItems(input.todos);
5057
+ }
5058
+ const inProgressCount = countInProgressTodos(nextTodos);
5059
+ if (inProgressCount > 1) {
5060
+ return `Invalid todo state: ${inProgressCount} items are in_progress. Keep at most one item in_progress so tasks can be handled one-by-one.`;
5061
+ }
5062
+ if (nextTodos.length === 0) {
5063
+ clearTodosForSession(todoSessionId);
5064
+ } else {
5065
+ setTodosForSession(todoSessionId, nextTodos);
5066
+ }
5067
+ return formatSuccess(mode, nextTodos);
4772
5068
  }
4773
5069
  });
4774
5070
 
@@ -4831,6 +5127,15 @@ import { promises as fs14 } from "fs";
4831
5127
  import path13 from "path";
4832
5128
  import { defineTool as defineTool15 } from "@codelia/core";
4833
5129
  import { z as z16 } from "zod";
5130
+ var buildDiffPreview = (content, filePath) => {
5131
+ const diff = createUnifiedDiff(filePath, "", content);
5132
+ if (!diff) {
5133
+ return `--- ${filePath}
5134
+ +++ ${filePath}
5135
+ @@ -0,0 +0,0 @@`;
5136
+ }
5137
+ return diff;
5138
+ };
4834
5139
  var createWriteTool = (sandboxKey) => defineTool15({
4835
5140
  name: "write",
4836
5141
  description: "Write text to a file, creating parent directories if needed.",
@@ -4849,7 +5154,12 @@ var createWriteTool = (sandboxKey) => defineTool15({
4849
5154
  try {
4850
5155
  await fs14.mkdir(path13.dirname(resolved), { recursive: true });
4851
5156
  await fs14.writeFile(resolved, input.content, "utf8");
4852
- return `Wrote ${input.content.length} bytes to ${input.file_path}`;
5157
+ const diff = buildDiffPreview(input.content, input.file_path);
5158
+ return {
5159
+ summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
5160
+ diff,
5161
+ file_path: input.file_path
5162
+ };
4853
5163
  } catch (error) {
4854
5164
  return `Error writing file: ${String(error)}`;
4855
5165
  }
@@ -4872,8 +5182,8 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
4872
5182
  createToolOutputCacheTool(options.toolOutputCacheStore),
4873
5183
  createToolOutputCacheGrepTool(options.toolOutputCacheStore)
4874
5184
  ] : [],
4875
- createTodoReadTool(sandboxKey),
4876
- createTodoWriteTool(sandboxKey),
5185
+ createTodoReadTool(sandboxKey, options.todoSessionContextKey),
5186
+ createTodoWriteTool(sandboxKey, options.todoSessionContextKey),
4877
5187
  createLaneCreateTool(sandboxKey),
4878
5188
  createLaneListTool(sandboxKey),
4879
5189
  createLaneStatusTool(sandboxKey),
@@ -5276,6 +5586,9 @@ var createAgentFactory = (state, options = {}) => {
5276
5586
  state.runtimeWorkingDir = ctx.workingDir;
5277
5587
  state.runtimeSandboxRoot = ctx.rootDir;
5278
5588
  const sandboxKey = createSandboxKey(ctx);
5589
+ const todoSessionContextKey = createToolSessionContextKey(
5590
+ () => state.sessionId
5591
+ );
5279
5592
  const agentsResolverKey = createAgentsResolverKey(agentsResolver);
5280
5593
  const skillsResolverKey = createSkillsResolverKey(skillsResolver);
5281
5594
  const toolOutputCacheStore = new ToolOutputCacheStoreImpl();
@@ -5284,7 +5597,8 @@ var createAgentFactory = (state, options = {}) => {
5284
5597
  agentsResolverKey,
5285
5598
  skillsResolverKey,
5286
5599
  {
5287
- toolOutputCacheStore
5600
+ toolOutputCacheStore,
5601
+ todoSessionContextKey
5288
5602
  }
5289
5603
  );
5290
5604
  const editTool = baseLocalTools.find(
@@ -5651,7 +5965,7 @@ var createAbortError = (message) => {
5651
5965
  error.name = "AbortError";
5652
5966
  return error;
5653
5967
  };
5654
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5968
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5655
5969
  var describeError = (error) => error instanceof Error ? error.message : String(error);
5656
5970
  var normalizeRpcError = (method, error) => new Error(`MCP ${method} error (${error.code}): ${error.message}`);
5657
5971
  var toLine = (value) => `${JSON.stringify(value)}
@@ -5687,7 +6001,7 @@ var matchesRequestId = (value, expectedRequestId) => {
5687
6001
  if (Array.isArray(value)) {
5688
6002
  return value.some((entry) => matchesRequestId(entry, expectedRequestId));
5689
6003
  }
5690
- if (!isRecord2(value)) return false;
6004
+ if (!isRecord3(value)) return false;
5691
6005
  const id = value.id;
5692
6006
  return typeof id === "string" || typeof id === "number" ? String(id) === expectedRequestId : false;
5693
6007
  };
@@ -5983,7 +6297,7 @@ var StdioMcpClient = class {
5983
6297
  });
5984
6298
  }
5985
6299
  handleRpcResponse(value) {
5986
- if (!isRecord2(value)) return;
6300
+ if (!isRecord3(value)) return;
5987
6301
  const message = value;
5988
6302
  if (message.id === void 0 || message.id === null) return;
5989
6303
  const requestId = String(message.id);
@@ -6112,13 +6426,13 @@ var StdioMcpClient = class {
6112
6426
  };
6113
6427
 
6114
6428
  // src/mcp/oauth-helpers.ts
6115
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6429
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6116
6430
  var parseStringArray = (value) => {
6117
6431
  if (!Array.isArray(value)) return [];
6118
6432
  return value.filter((entry) => typeof entry === "string");
6119
6433
  };
6120
6434
  var parseProtectedResourceMetadata = (value) => {
6121
- if (!isRecord3(value)) return null;
6435
+ if (!isRecord4(value)) return null;
6122
6436
  return {
6123
6437
  ...typeof value.resource === "string" ? { resource: value.resource } : {},
6124
6438
  ...typeof value.token_endpoint === "string" ? { token_endpoint: value.token_endpoint } : {},
@@ -6127,7 +6441,7 @@ var parseProtectedResourceMetadata = (value) => {
6127
6441
  };
6128
6442
  };
6129
6443
  var parseAuthorizationServerMetadata = (value) => {
6130
- if (!isRecord3(value)) return null;
6444
+ if (!isRecord4(value)) return null;
6131
6445
  return {
6132
6446
  ...typeof value.issuer === "string" ? { issuer: value.issuer } : {},
6133
6447
  ...typeof value.authorization_endpoint === "string" ? { authorization_endpoint: value.authorization_endpoint } : {},
@@ -6151,7 +6465,7 @@ var buildAuthorizationServerMetadataUrl = (issuer) => {
6151
6465
  }
6152
6466
  };
6153
6467
  var parseTokenResponse = (value, current) => {
6154
- if (!isRecord3(value) || typeof value.access_token !== "string") {
6468
+ if (!isRecord4(value) || typeof value.access_token !== "string") {
6155
6469
  throw new Error("OAuth token response missing access_token");
6156
6470
  }
6157
6471
  const expiresIn = typeof value.expires_in === "number" && Number.isFinite(value.expires_in) ? value.expires_in : void 0;
@@ -6244,8 +6558,8 @@ import crypto5 from "crypto";
6244
6558
  var MAX_SCHEMA_SIZE_BYTES = 64 * 1024;
6245
6559
  var MAX_TOOL_OUTPUT_CHARS = 1e5;
6246
6560
  var MAX_TOOLS_LIST_PAGES = 100;
6247
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6248
- var isMcpToolDescriptor = (value) => isRecord4(value) && typeof value.name === "string";
6561
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6562
+ var isMcpToolDescriptor = (value) => isRecord5(value) && typeof value.name === "string";
6249
6563
  var toSlug2 = (value) => {
6250
6564
  const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
6251
6565
  return slug || "tool";
@@ -6268,7 +6582,7 @@ var fallbackSchema = () => ({
6268
6582
  additionalProperties: true
6269
6583
  });
6270
6584
  var normalizeSchema = (value) => {
6271
- if (!isRecord4(value)) return fallbackSchema();
6585
+ if (!isRecord5(value)) return fallbackSchema();
6272
6586
  let encoded = "";
6273
6587
  try {
6274
6588
  encoded = JSON.stringify(value);
@@ -6282,7 +6596,7 @@ var normalizeSchema = (value) => {
6282
6596
  };
6283
6597
  var stringifyMcpContentItem = (value) => {
6284
6598
  if (typeof value === "string") return value;
6285
- if (!isRecord4(value)) return JSON.stringify(value);
6599
+ if (!isRecord5(value)) return JSON.stringify(value);
6286
6600
  if (typeof value.text === "string") return value.text;
6287
6601
  try {
6288
6602
  return JSON.stringify(value);
@@ -6297,7 +6611,7 @@ var truncateText = (value, maxChars) => {
6297
6611
  };
6298
6612
  var toolResultToText = (value) => {
6299
6613
  if (typeof value === "string") return value;
6300
- if (!isRecord4(value)) {
6614
+ if (!isRecord5(value)) {
6301
6615
  try {
6302
6616
  return JSON.stringify(value);
6303
6617
  } catch {
@@ -6328,26 +6642,26 @@ var toolResultToText = (value) => {
6328
6642
  }
6329
6643
  };
6330
6644
  var parseNextCursor = (value) => {
6331
- if (!isRecord4(value)) return void 0;
6645
+ if (!isRecord5(value)) return void 0;
6332
6646
  if (typeof value.nextCursor === "string") return value.nextCursor;
6333
6647
  if (typeof value.next_cursor === "string") return value.next_cursor;
6334
6648
  return void 0;
6335
6649
  };
6336
6650
  var parseToolsList = (value) => {
6337
- if (!isRecord4(value) || !Array.isArray(value.tools)) return [];
6651
+ if (!isRecord5(value) || !Array.isArray(value.tools)) return [];
6338
6652
  return value.tools.filter(
6339
6653
  (entry) => isMcpToolDescriptor(entry)
6340
6654
  );
6341
6655
  };
6342
6656
  var isCallErrorResult = (value) => {
6343
- if (!isRecord4(value)) return false;
6657
+ if (!isRecord5(value)) return false;
6344
6658
  if (value.isError === true) return true;
6345
6659
  if (value.is_error === true) return true;
6346
6660
  return false;
6347
6661
  };
6348
6662
  var hasToolCapability = (value) => {
6349
- if (!isRecord4(value)) return false;
6350
- const caps = isRecord4(value.capabilities) ? value.capabilities : null;
6663
+ if (!isRecord5(value)) return false;
6664
+ const caps = isRecord5(value.capabilities) ? value.capabilities : null;
6351
6665
  if (!caps) return false;
6352
6666
  return caps.tools !== void 0;
6353
6667
  };
@@ -7965,14 +8279,21 @@ var createSessionAppender = (store, onError) => {
7965
8279
  });
7966
8280
  };
7967
8281
  };
7968
- var buildSessionState = (sessionId, runId, messages, invokeSeq) => ({
8282
+ var buildSessionState = (sessionId, runId, messages, invokeSeq, meta) => ({
7969
8283
  schema_version: 1,
7970
8284
  session_id: sessionId,
7971
8285
  updated_at: nowIso4(),
7972
8286
  run_id: runId,
7973
8287
  invoke_seq: invokeSeq,
7974
- messages
8288
+ messages,
8289
+ meta
7975
8290
  });
8291
+ var toMetaObject = (value) => {
8292
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
8293
+ return void 0;
8294
+ }
8295
+ return { ...value };
8296
+ };
7976
8297
  var toTimestampMs = (value) => {
7977
8298
  const ms = Date.parse(value);
7978
8299
  return Number.isFinite(ms) ? ms : null;
@@ -8066,7 +8387,9 @@ var createRunHandlers = ({
8066
8387
  }
8067
8388
  const requestedSessionId = params.session_id?.trim() || void 0;
8068
8389
  let resumeState = null;
8390
+ const previousSessionId = state.sessionId;
8069
8391
  let sessionId = requestedSessionId ?? state.sessionId ?? state.nextSessionId();
8392
+ let loadedSessionState = false;
8070
8393
  if (requestedSessionId && requestedSessionId !== state.sessionId) {
8071
8394
  try {
8072
8395
  resumeState = await sessionStateStore.load(requestedSessionId);
@@ -8092,6 +8415,7 @@ var createRunHandlers = ({
8092
8415
  runtimeAgent.replaceHistoryMessages(messages);
8093
8416
  sessionId = requestedSessionId;
8094
8417
  state.sessionId = sessionId;
8418
+ loadedSessionState = true;
8095
8419
  } else if (state.sessionId && runtimeAgent.getHistoryMessages().length === 0) {
8096
8420
  try {
8097
8421
  resumeState = await sessionStateStore.load(state.sessionId);
@@ -8109,10 +8433,31 @@ var createRunHandlers = ({
8109
8433
  state.sessionId
8110
8434
  );
8111
8435
  runtimeAgent.replaceHistoryMessages(messages);
8436
+ loadedSessionState = true;
8112
8437
  }
8113
8438
  } else if (!state.sessionId) {
8114
8439
  state.sessionId = sessionId;
8115
8440
  }
8441
+ const switchedSession = previousSessionId !== sessionId;
8442
+ if (loadedSessionState && resumeState) {
8443
+ const restoredTodos = readTodosFromSessionMeta(resumeState.meta);
8444
+ if (restoredTodos.length > 0) {
8445
+ setTodosForSession(sessionId, restoredTodos);
8446
+ } else {
8447
+ clearTodosForSession(sessionId);
8448
+ }
8449
+ state.sessionMeta = toMetaObject(resumeState.meta) ?? null;
8450
+ } else if (switchedSession) {
8451
+ clearTodosForSession(sessionId);
8452
+ state.sessionMeta = null;
8453
+ }
8454
+ const runMeta = toMetaObject(params.meta);
8455
+ if (runMeta) {
8456
+ state.sessionMeta = {
8457
+ ...state.sessionMeta ?? {},
8458
+ ...runMeta
8459
+ };
8460
+ }
8116
8461
  const runId = state.nextRunId();
8117
8462
  const startedAt = nowIso4();
8118
8463
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
@@ -8261,13 +8606,19 @@ var createRunHandlers = ({
8261
8606
  `session.save normalized reason=${reason}`
8262
8607
  );
8263
8608
  }
8609
+ const sessionMeta = mergeTodosIntoSessionMeta(
8610
+ state.sessionMeta ?? void 0,
8611
+ getTodosForSession(sessionId)
8612
+ );
8264
8613
  const snapshot = buildSessionState(
8265
8614
  sessionId,
8266
8615
  runId,
8267
8616
  snapshotMessages,
8268
- session.invoke_seq
8617
+ session.invoke_seq,
8618
+ sessionMeta
8269
8619
  );
8270
8620
  await sessionStateStore.save(snapshot);
8621
+ state.sessionMeta = sessionMeta ?? null;
8271
8622
  logRunDebug(log2, runId, `session.save ${reason}`);
8272
8623
  }).catch((error) => {
8273
8624
  log2(`Error: session-state save failed: ${String(error)}`);
@@ -9148,6 +9499,7 @@ var createRuntimeHandlers = ({
9148
9499
  state.agent = null;
9149
9500
  if (clearSession) {
9150
9501
  state.sessionId = null;
9502
+ state.sessionMeta = null;
9151
9503
  state.sessionAppend = null;
9152
9504
  }
9153
9505
  const result = {
@@ -9244,6 +9596,7 @@ var RuntimeState = class {
9244
9596
  toolDefinitions = null;
9245
9597
  tools = null;
9246
9598
  sessionId = null;
9599
+ sessionMeta = null;
9247
9600
  sessionAppend = null;
9248
9601
  agent = null;
9249
9602
  agentsResolver = null;