@codelia/storage 0.1.44 → 0.1.45

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.cjs CHANGED
@@ -36,6 +36,7 @@ __export(index_exports, {
36
36
  SessionStateStoreImpl: () => SessionStateStoreImpl,
37
37
  SessionStoreWriterImpl: () => SessionStoreWriterImpl,
38
38
  StoragePathServiceImpl: () => StoragePathServiceImpl,
39
+ TaskRegistryStore: () => TaskRegistryStore,
39
40
  ToolOutputCacheStoreImpl: () => ToolOutputCacheStoreImpl,
40
41
  ensureStorageDirs: () => ensureStorageDirs,
41
42
  resolveStoragePaths: () => resolveStoragePaths
@@ -767,9 +768,215 @@ var SessionStateStoreImpl = class {
767
768
  }
768
769
  };
769
770
 
770
- // src/tool-output-cache.ts
771
+ // src/task-registry.ts
771
772
  var import_node_fs5 = require("fs");
772
773
  var import_node_path5 = __toESM(require("path"), 1);
774
+ var TASKS_DIRNAME = "tasks";
775
+ var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
776
+ var toShellKeyBase = (label) => {
777
+ const source = label?.trim() ?? "";
778
+ const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
779
+ return slug || "shell";
780
+ };
781
+ var compactTaskId = (taskId) => {
782
+ const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
783
+ return compact || taskId.toLowerCase();
784
+ };
785
+ var assignMissingShellKeys = (tasks) => {
786
+ const usedKeys = new Set(
787
+ tasks.map((task) => task.key).filter((key) => typeof key === "string" && key.length > 0)
788
+ );
789
+ const updates = [];
790
+ for (const task of tasks) {
791
+ if (task.kind !== "shell" || typeof task.key === "string" && task.key.length > 0) {
792
+ continue;
793
+ }
794
+ const base = toShellKeyBase(task.label);
795
+ const compactIdValue = compactTaskId(task.task_id);
796
+ let nextKey = "";
797
+ for (const length of [8, 12, compactIdValue.length]) {
798
+ const suffix = compactIdValue.slice(0, Math.min(length, compactIdValue.length));
799
+ if (!suffix) continue;
800
+ const candidate = `${base}-${suffix}`;
801
+ if (!usedKeys.has(candidate)) {
802
+ nextKey = candidate;
803
+ break;
804
+ }
805
+ }
806
+ if (!nextKey) {
807
+ let counter = 2;
808
+ nextKey = `${base}-${compactIdValue}`;
809
+ while (usedKeys.has(nextKey)) {
810
+ nextKey = `${base}-${compactIdValue}-${counter}`;
811
+ counter += 1;
812
+ }
813
+ }
814
+ usedKeys.add(nextKey);
815
+ updates.push({
816
+ original: task,
817
+ next: {
818
+ ...task,
819
+ key: nextKey
820
+ }
821
+ });
822
+ }
823
+ return updates;
824
+ };
825
+ var atomicWrite = async (filePath, payload) => {
826
+ const dir = import_node_path5.default.dirname(filePath);
827
+ const base = import_node_path5.default.basename(filePath);
828
+ const tmp = import_node_path5.default.join(
829
+ dir,
830
+ `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
831
+ );
832
+ await import_node_fs5.promises.writeFile(tmp, payload, "utf8");
833
+ await import_node_fs5.promises.rename(tmp, filePath);
834
+ };
835
+ var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
836
+ var isTaskKind = (value) => value === "shell" || value === "subagent";
837
+ var isWorkspaceMode = (value) => value === "live_workspace" || value === "worktree";
838
+ var isString = (value) => typeof value === "string";
839
+ var isNumber = (value) => typeof value === "number" && Number.isFinite(value);
840
+ var isTaskArtifact = (value) => {
841
+ if (!value || typeof value !== "object") return false;
842
+ const artifact = value;
843
+ return (artifact.type === "file" || artifact.type === "patch" || artifact.type === "json") && (artifact.path === void 0 || isString(artifact.path)) && (artifact.ref === void 0 || isString(artifact.ref)) && (artifact.description === void 0 || isString(artifact.description));
844
+ };
845
+ var isTaskTruncatedOutput = (value) => {
846
+ if (!value || typeof value !== "object") return false;
847
+ const truncated = value;
848
+ return typeof truncated.stdout === "boolean" && typeof truncated.stderr === "boolean" && typeof truncated.combined === "boolean";
849
+ };
850
+ var isTaskResult = (value) => {
851
+ if (!value || typeof value !== "object") return false;
852
+ const result = value;
853
+ return (result.summary === void 0 || isString(result.summary)) && (result.stdout === void 0 || isString(result.stdout)) && (result.stderr === void 0 || isString(result.stderr)) && (result.stdout_cache_id === void 0 || isString(result.stdout_cache_id)) && (result.stderr_cache_id === void 0 || isString(result.stderr_cache_id)) && (result.child_session_id === void 0 || isString(result.child_session_id)) && (result.worktree_path === void 0 || isString(result.worktree_path)) && (result.exit_code === void 0 || result.exit_code === null || isNumber(result.exit_code)) && (result.signal === void 0 || result.signal === null || isString(result.signal)) && (result.duration_ms === void 0 || isNumber(result.duration_ms)) && (result.truncated === void 0 || isTaskTruncatedOutput(result.truncated)) && (result.artifacts === void 0 || Array.isArray(result.artifacts) && result.artifacts.every(isTaskArtifact));
854
+ };
855
+ var normalizeTaskRecord = (value) => {
856
+ if (!value || typeof value !== "object") return null;
857
+ const record = value;
858
+ if (record.version !== 1 || !isString(record.task_id) || !isTaskKind(record.kind) || !isWorkspaceMode(record.workspace_mode) || !isTaskState(record.state) || !isString(record.owner_runtime_id) || !isNumber(record.owner_pid) || !isString(record.created_at) || !isString(record.updated_at)) {
859
+ return null;
860
+ }
861
+ if (record.key !== void 0 && !isString(record.key)) {
862
+ return null;
863
+ }
864
+ if (record.label !== void 0 && !isString(record.label)) {
865
+ return null;
866
+ }
867
+ if (record.title !== void 0 && !isString(record.title)) {
868
+ return null;
869
+ }
870
+ if (record.working_directory !== void 0 && !isString(record.working_directory)) {
871
+ return null;
872
+ }
873
+ if (record.executor_pid !== void 0 && !isNumber(record.executor_pid)) {
874
+ return null;
875
+ }
876
+ if (record.executor_pgid !== void 0 && !isNumber(record.executor_pgid)) {
877
+ return null;
878
+ }
879
+ if (record.parent_session_id !== void 0 && !isString(record.parent_session_id)) {
880
+ return null;
881
+ }
882
+ if (record.parent_run_id !== void 0 && !isString(record.parent_run_id)) {
883
+ return null;
884
+ }
885
+ if (record.parent_tool_call_id !== void 0 && !isString(record.parent_tool_call_id)) {
886
+ return null;
887
+ }
888
+ if (record.child_session_id !== void 0 && !isString(record.child_session_id)) {
889
+ return null;
890
+ }
891
+ if (record.started_at !== void 0 && !isString(record.started_at)) {
892
+ return null;
893
+ }
894
+ if (record.ended_at !== void 0 && !isString(record.ended_at)) {
895
+ return null;
896
+ }
897
+ if (record.result !== void 0 && !isTaskResult(record.result)) {
898
+ return null;
899
+ }
900
+ if (record.failure_message !== void 0 && !isString(record.failure_message)) {
901
+ return null;
902
+ }
903
+ if (record.cancellation_reason !== void 0 && !isString(record.cancellation_reason)) {
904
+ return null;
905
+ }
906
+ if (record.cleanup_reason !== void 0 && !isString(record.cleanup_reason)) {
907
+ return null;
908
+ }
909
+ return record;
910
+ };
911
+ var readTaskFile = async (filePath) => {
912
+ try {
913
+ const raw = await import_node_fs5.promises.readFile(filePath, "utf8");
914
+ return normalizeTaskRecord(JSON.parse(raw));
915
+ } catch {
916
+ return null;
917
+ }
918
+ };
919
+ var taskFileName = (taskId) => `${encodeURIComponent(taskId)}.json`;
920
+ var TaskRegistryStore = class {
921
+ tasksDir;
922
+ constructor(tasksDir) {
923
+ if (tasksDir) {
924
+ this.tasksDir = tasksDir;
925
+ return;
926
+ }
927
+ const root = resolveStoragePaths().root;
928
+ this.tasksDir = import_node_path5.default.join(root, TASKS_DIRNAME);
929
+ }
930
+ async ensureDir() {
931
+ await import_node_fs5.promises.mkdir(this.tasksDir, { recursive: true });
932
+ }
933
+ taskPath(taskId) {
934
+ return import_node_path5.default.join(this.tasksDir, taskFileName(taskId));
935
+ }
936
+ async list() {
937
+ await this.ensureDir();
938
+ const entries = await import_node_fs5.promises.readdir(this.tasksDir, { withFileTypes: true });
939
+ const tasks = (await Promise.all(
940
+ entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(import_node_path5.default.join(this.tasksDir, entry.name)))
941
+ )).filter((task) => task !== null);
942
+ const keyBackfills = assignMissingShellKeys(tasks);
943
+ if (keyBackfills.length > 0) {
944
+ await Promise.all(keyBackfills.map(({ next }) => this.upsert(next)));
945
+ const byId = new Map(keyBackfills.map(({ next }) => [next.task_id, next]));
946
+ return sortByUpdatedDesc(tasks.map((task) => byId.get(task.task_id) ?? task));
947
+ }
948
+ return sortByUpdatedDesc(tasks);
949
+ }
950
+ async get(taskId) {
951
+ const tasks = await this.list();
952
+ return tasks.find((task) => task.task_id === taskId) ?? null;
953
+ }
954
+ async upsert(record) {
955
+ await this.ensureDir();
956
+ await atomicWrite(
957
+ this.taskPath(record.task_id),
958
+ `${JSON.stringify(record, null, 2)}
959
+ `
960
+ );
961
+ }
962
+ async patch(taskId, patch) {
963
+ const current = await this.get(taskId);
964
+ if (!current) return null;
965
+ const next = {
966
+ ...current,
967
+ ...patch,
968
+ version: 1,
969
+ task_id: current.task_id,
970
+ created_at: current.created_at
971
+ };
972
+ await this.upsert(next);
973
+ return next;
974
+ }
975
+ };
976
+
977
+ // src/tool-output-cache.ts
978
+ var import_node_fs6 = require("fs");
979
+ var import_node_path6 = __toESM(require("path"), 1);
773
980
  var DEFAULT_MAX_MATCHES = 50;
774
981
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
775
982
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -873,15 +1080,15 @@ var ToolOutputCacheStoreImpl = class {
873
1080
  async save(record) {
874
1081
  const refId = normalizeRefId(record.tool_call_id);
875
1082
  const filePath = this.resolvePath(refId);
876
- await import_node_fs5.promises.mkdir(this.baseDir, { recursive: true });
877
- await import_node_fs5.promises.writeFile(filePath, record.content, "utf8");
1083
+ await import_node_fs6.promises.mkdir(this.baseDir, { recursive: true });
1084
+ await import_node_fs6.promises.writeFile(filePath, record.content, "utf8");
878
1085
  const byteSize = Buffer.byteLength(record.content, "utf8");
879
1086
  const lineCount = record.content.split(/\r?\n/).length;
880
1087
  return { id: refId, byte_size: byteSize, line_count: lineCount };
881
1088
  }
882
1089
  async read(refId, options = {}) {
883
1090
  const filePath = this.resolvePath(refId);
884
- const content = await import_node_fs5.promises.readFile(filePath, "utf8");
1091
+ const content = await import_node_fs6.promises.readFile(filePath, "utf8");
885
1092
  const lines = content.split(/\r?\n/);
886
1093
  const offset = options.offset ?? 0;
887
1094
  const limit = options.limit ?? lines.length;
@@ -938,9 +1145,21 @@ var ToolOutputCacheStoreImpl = class {
938
1145
  For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).` : ""
939
1146
  );
940
1147
  }
1148
+ async readTail(refId, options) {
1149
+ const filePath = this.resolvePath(refId);
1150
+ const content = await import_node_fs6.promises.readFile(filePath, "utf8");
1151
+ const lines = content.split(/\r?\n/);
1152
+ const tailLines = Math.max(1, Math.trunc(options.tail_lines));
1153
+ const start = Math.max(0, lines.length - tailLines);
1154
+ return {
1155
+ content: lines.slice(start).join("\n"),
1156
+ total_lines: lines.length,
1157
+ omitted_lines: start
1158
+ };
1159
+ }
941
1160
  async readLine(refId, options) {
942
1161
  const filePath = this.resolvePath(refId);
943
- const content = await import_node_fs5.promises.readFile(filePath, "utf8");
1162
+ const content = await import_node_fs6.promises.readFile(filePath, "utf8");
944
1163
  const lines = content.split(/\r?\n/);
945
1164
  const lineIndex = options.line_number - 1;
946
1165
  if (lineIndex < 0 || lineIndex >= lines.length) {
@@ -979,7 +1198,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
979
1198
  }
980
1199
  async grep(refId, options) {
981
1200
  const filePath = this.resolvePath(refId);
982
- const content = await import_node_fs5.promises.readFile(filePath, "utf8");
1201
+ const content = await import_node_fs6.promises.readFile(filePath, "utf8");
983
1202
  const lines = content.split(/\r?\n/);
984
1203
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
985
1204
  const before = Math.max(0, options.before ?? 0);
@@ -1030,7 +1249,7 @@ ${snippet}`;
1030
1249
  return output;
1031
1250
  }
1032
1251
  resolvePath(refId) {
1033
- return import_node_path5.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1252
+ return import_node_path6.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1034
1253
  }
1035
1254
  };
1036
1255
  // Annotate the CommonJS export names for ESM import in node:
@@ -1041,6 +1260,7 @@ ${snippet}`;
1041
1260
  SessionStateStoreImpl,
1042
1261
  SessionStoreWriterImpl,
1043
1262
  StoragePathServiceImpl,
1263
+ TaskRegistryStore,
1044
1264
  ToolOutputCacheStoreImpl,
1045
1265
  ensureStorageDirs,
1046
1266
  resolveStoragePaths
package/dist/index.d.cts CHANGED
@@ -95,6 +95,72 @@ declare class SessionStoreWriterImpl implements SessionStore {
95
95
  append(record: SessionRecord): Promise<void>;
96
96
  }
97
97
 
98
+ type TaskState = "queued" | "running" | "completed" | "failed" | "cancelled";
99
+ type TaskKind = "shell" | "subagent";
100
+ type TaskWorkspaceMode = "live_workspace" | "worktree";
101
+ type TaskArtifact = {
102
+ type: "file" | "patch" | "json";
103
+ path?: string;
104
+ ref?: string;
105
+ description?: string;
106
+ };
107
+ type TaskTruncatedOutput = {
108
+ stdout: boolean;
109
+ stderr: boolean;
110
+ combined: boolean;
111
+ };
112
+ type TaskResult = {
113
+ summary?: string;
114
+ stdout?: string;
115
+ stderr?: string;
116
+ stdout_cache_id?: string;
117
+ stderr_cache_id?: string;
118
+ child_session_id?: string;
119
+ worktree_path?: string;
120
+ exit_code?: number | null;
121
+ signal?: string | null;
122
+ duration_ms?: number;
123
+ truncated?: TaskTruncatedOutput;
124
+ artifacts?: TaskArtifact[];
125
+ };
126
+ type TaskRecord = {
127
+ version: 1;
128
+ task_id: string;
129
+ kind: TaskKind;
130
+ workspace_mode: TaskWorkspaceMode;
131
+ state: TaskState;
132
+ owner_runtime_id: string;
133
+ owner_pid: number;
134
+ key?: string;
135
+ label?: string;
136
+ title?: string;
137
+ working_directory?: string;
138
+ executor_pid?: number;
139
+ executor_pgid?: number;
140
+ parent_session_id?: string;
141
+ parent_run_id?: string;
142
+ parent_tool_call_id?: string;
143
+ child_session_id?: string;
144
+ created_at: string;
145
+ updated_at: string;
146
+ started_at?: string;
147
+ ended_at?: string;
148
+ result?: TaskResult;
149
+ failure_message?: string;
150
+ cancellation_reason?: string;
151
+ cleanup_reason?: string;
152
+ };
153
+ declare class TaskRegistryStore {
154
+ private readonly tasksDir;
155
+ constructor(tasksDir?: string);
156
+ private ensureDir;
157
+ private taskPath;
158
+ list(): Promise<TaskRecord[]>;
159
+ get(taskId: string): Promise<TaskRecord | null>;
160
+ upsert(record: TaskRecord): Promise<void>;
161
+ patch(taskId: string, patch: Partial<Omit<TaskRecord, "version" | "task_id" | "created_at">>): Promise<TaskRecord | null>;
162
+ }
163
+
98
164
  type ToolOutputCacheLimits = {
99
165
  maxLineLength?: number;
100
166
  maxReadBytes?: number;
@@ -111,6 +177,13 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
111
177
  });
112
178
  save(record: ToolOutputCacheRecord): Promise<ToolOutputRef>;
113
179
  read(refId: string, options?: ToolOutputCacheReadOptions): Promise<string>;
180
+ readTail(refId: string, options: {
181
+ tail_lines: number;
182
+ }): Promise<{
183
+ content: string;
184
+ total_lines: number;
185
+ omitted_lines: number;
186
+ }>;
114
187
  readLine(refId: string, options: {
115
188
  line_number: number;
116
189
  char_offset?: number;
@@ -120,4 +193,4 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
120
193
  private resolvePath;
121
194
  }
122
195
 
123
- export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
196
+ export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, type TaskArtifact, type TaskKind, type TaskRecord, TaskRegistryStore, type TaskResult, type TaskState, type TaskTruncatedOutput, type TaskWorkspaceMode, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
package/dist/index.d.ts CHANGED
@@ -95,6 +95,72 @@ declare class SessionStoreWriterImpl implements SessionStore {
95
95
  append(record: SessionRecord): Promise<void>;
96
96
  }
97
97
 
98
+ type TaskState = "queued" | "running" | "completed" | "failed" | "cancelled";
99
+ type TaskKind = "shell" | "subagent";
100
+ type TaskWorkspaceMode = "live_workspace" | "worktree";
101
+ type TaskArtifact = {
102
+ type: "file" | "patch" | "json";
103
+ path?: string;
104
+ ref?: string;
105
+ description?: string;
106
+ };
107
+ type TaskTruncatedOutput = {
108
+ stdout: boolean;
109
+ stderr: boolean;
110
+ combined: boolean;
111
+ };
112
+ type TaskResult = {
113
+ summary?: string;
114
+ stdout?: string;
115
+ stderr?: string;
116
+ stdout_cache_id?: string;
117
+ stderr_cache_id?: string;
118
+ child_session_id?: string;
119
+ worktree_path?: string;
120
+ exit_code?: number | null;
121
+ signal?: string | null;
122
+ duration_ms?: number;
123
+ truncated?: TaskTruncatedOutput;
124
+ artifacts?: TaskArtifact[];
125
+ };
126
+ type TaskRecord = {
127
+ version: 1;
128
+ task_id: string;
129
+ kind: TaskKind;
130
+ workspace_mode: TaskWorkspaceMode;
131
+ state: TaskState;
132
+ owner_runtime_id: string;
133
+ owner_pid: number;
134
+ key?: string;
135
+ label?: string;
136
+ title?: string;
137
+ working_directory?: string;
138
+ executor_pid?: number;
139
+ executor_pgid?: number;
140
+ parent_session_id?: string;
141
+ parent_run_id?: string;
142
+ parent_tool_call_id?: string;
143
+ child_session_id?: string;
144
+ created_at: string;
145
+ updated_at: string;
146
+ started_at?: string;
147
+ ended_at?: string;
148
+ result?: TaskResult;
149
+ failure_message?: string;
150
+ cancellation_reason?: string;
151
+ cleanup_reason?: string;
152
+ };
153
+ declare class TaskRegistryStore {
154
+ private readonly tasksDir;
155
+ constructor(tasksDir?: string);
156
+ private ensureDir;
157
+ private taskPath;
158
+ list(): Promise<TaskRecord[]>;
159
+ get(taskId: string): Promise<TaskRecord | null>;
160
+ upsert(record: TaskRecord): Promise<void>;
161
+ patch(taskId: string, patch: Partial<Omit<TaskRecord, "version" | "task_id" | "created_at">>): Promise<TaskRecord | null>;
162
+ }
163
+
98
164
  type ToolOutputCacheLimits = {
99
165
  maxLineLength?: number;
100
166
  maxReadBytes?: number;
@@ -111,6 +177,13 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
111
177
  });
112
178
  save(record: ToolOutputCacheRecord): Promise<ToolOutputRef>;
113
179
  read(refId: string, options?: ToolOutputCacheReadOptions): Promise<string>;
180
+ readTail(refId: string, options: {
181
+ tail_lines: number;
182
+ }): Promise<{
183
+ content: string;
184
+ total_lines: number;
185
+ omitted_lines: number;
186
+ }>;
114
187
  readLine(refId: string, options: {
115
188
  line_number: number;
116
189
  char_offset?: number;
@@ -120,4 +193,4 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
120
193
  private resolvePath;
121
194
  }
122
195
 
123
- export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
196
+ export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, type TaskArtifact, type TaskKind, type TaskRecord, TaskRegistryStore, type TaskResult, type TaskState, type TaskTruncatedOutput, type TaskWorkspaceMode, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
package/dist/index.js CHANGED
@@ -723,9 +723,215 @@ var SessionStateStoreImpl = class {
723
723
  }
724
724
  };
725
725
 
726
- // src/tool-output-cache.ts
726
+ // src/task-registry.ts
727
727
  import { promises as fs5 } from "fs";
728
728
  import path5 from "path";
729
+ var TASKS_DIRNAME = "tasks";
730
+ var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
731
+ var toShellKeyBase = (label) => {
732
+ const source = label?.trim() ?? "";
733
+ const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
734
+ return slug || "shell";
735
+ };
736
+ var compactTaskId = (taskId) => {
737
+ const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
738
+ return compact || taskId.toLowerCase();
739
+ };
740
+ var assignMissingShellKeys = (tasks) => {
741
+ const usedKeys = new Set(
742
+ tasks.map((task) => task.key).filter((key) => typeof key === "string" && key.length > 0)
743
+ );
744
+ const updates = [];
745
+ for (const task of tasks) {
746
+ if (task.kind !== "shell" || typeof task.key === "string" && task.key.length > 0) {
747
+ continue;
748
+ }
749
+ const base = toShellKeyBase(task.label);
750
+ const compactIdValue = compactTaskId(task.task_id);
751
+ let nextKey = "";
752
+ for (const length of [8, 12, compactIdValue.length]) {
753
+ const suffix = compactIdValue.slice(0, Math.min(length, compactIdValue.length));
754
+ if (!suffix) continue;
755
+ const candidate = `${base}-${suffix}`;
756
+ if (!usedKeys.has(candidate)) {
757
+ nextKey = candidate;
758
+ break;
759
+ }
760
+ }
761
+ if (!nextKey) {
762
+ let counter = 2;
763
+ nextKey = `${base}-${compactIdValue}`;
764
+ while (usedKeys.has(nextKey)) {
765
+ nextKey = `${base}-${compactIdValue}-${counter}`;
766
+ counter += 1;
767
+ }
768
+ }
769
+ usedKeys.add(nextKey);
770
+ updates.push({
771
+ original: task,
772
+ next: {
773
+ ...task,
774
+ key: nextKey
775
+ }
776
+ });
777
+ }
778
+ return updates;
779
+ };
780
+ var atomicWrite = async (filePath, payload) => {
781
+ const dir = path5.dirname(filePath);
782
+ const base = path5.basename(filePath);
783
+ const tmp = path5.join(
784
+ dir,
785
+ `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
786
+ );
787
+ await fs5.writeFile(tmp, payload, "utf8");
788
+ await fs5.rename(tmp, filePath);
789
+ };
790
+ var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
791
+ var isTaskKind = (value) => value === "shell" || value === "subagent";
792
+ var isWorkspaceMode = (value) => value === "live_workspace" || value === "worktree";
793
+ var isString = (value) => typeof value === "string";
794
+ var isNumber = (value) => typeof value === "number" && Number.isFinite(value);
795
+ var isTaskArtifact = (value) => {
796
+ if (!value || typeof value !== "object") return false;
797
+ const artifact = value;
798
+ return (artifact.type === "file" || artifact.type === "patch" || artifact.type === "json") && (artifact.path === void 0 || isString(artifact.path)) && (artifact.ref === void 0 || isString(artifact.ref)) && (artifact.description === void 0 || isString(artifact.description));
799
+ };
800
+ var isTaskTruncatedOutput = (value) => {
801
+ if (!value || typeof value !== "object") return false;
802
+ const truncated = value;
803
+ return typeof truncated.stdout === "boolean" && typeof truncated.stderr === "boolean" && typeof truncated.combined === "boolean";
804
+ };
805
+ var isTaskResult = (value) => {
806
+ if (!value || typeof value !== "object") return false;
807
+ const result = value;
808
+ return (result.summary === void 0 || isString(result.summary)) && (result.stdout === void 0 || isString(result.stdout)) && (result.stderr === void 0 || isString(result.stderr)) && (result.stdout_cache_id === void 0 || isString(result.stdout_cache_id)) && (result.stderr_cache_id === void 0 || isString(result.stderr_cache_id)) && (result.child_session_id === void 0 || isString(result.child_session_id)) && (result.worktree_path === void 0 || isString(result.worktree_path)) && (result.exit_code === void 0 || result.exit_code === null || isNumber(result.exit_code)) && (result.signal === void 0 || result.signal === null || isString(result.signal)) && (result.duration_ms === void 0 || isNumber(result.duration_ms)) && (result.truncated === void 0 || isTaskTruncatedOutput(result.truncated)) && (result.artifacts === void 0 || Array.isArray(result.artifacts) && result.artifacts.every(isTaskArtifact));
809
+ };
810
+ var normalizeTaskRecord = (value) => {
811
+ if (!value || typeof value !== "object") return null;
812
+ const record = value;
813
+ if (record.version !== 1 || !isString(record.task_id) || !isTaskKind(record.kind) || !isWorkspaceMode(record.workspace_mode) || !isTaskState(record.state) || !isString(record.owner_runtime_id) || !isNumber(record.owner_pid) || !isString(record.created_at) || !isString(record.updated_at)) {
814
+ return null;
815
+ }
816
+ if (record.key !== void 0 && !isString(record.key)) {
817
+ return null;
818
+ }
819
+ if (record.label !== void 0 && !isString(record.label)) {
820
+ return null;
821
+ }
822
+ if (record.title !== void 0 && !isString(record.title)) {
823
+ return null;
824
+ }
825
+ if (record.working_directory !== void 0 && !isString(record.working_directory)) {
826
+ return null;
827
+ }
828
+ if (record.executor_pid !== void 0 && !isNumber(record.executor_pid)) {
829
+ return null;
830
+ }
831
+ if (record.executor_pgid !== void 0 && !isNumber(record.executor_pgid)) {
832
+ return null;
833
+ }
834
+ if (record.parent_session_id !== void 0 && !isString(record.parent_session_id)) {
835
+ return null;
836
+ }
837
+ if (record.parent_run_id !== void 0 && !isString(record.parent_run_id)) {
838
+ return null;
839
+ }
840
+ if (record.parent_tool_call_id !== void 0 && !isString(record.parent_tool_call_id)) {
841
+ return null;
842
+ }
843
+ if (record.child_session_id !== void 0 && !isString(record.child_session_id)) {
844
+ return null;
845
+ }
846
+ if (record.started_at !== void 0 && !isString(record.started_at)) {
847
+ return null;
848
+ }
849
+ if (record.ended_at !== void 0 && !isString(record.ended_at)) {
850
+ return null;
851
+ }
852
+ if (record.result !== void 0 && !isTaskResult(record.result)) {
853
+ return null;
854
+ }
855
+ if (record.failure_message !== void 0 && !isString(record.failure_message)) {
856
+ return null;
857
+ }
858
+ if (record.cancellation_reason !== void 0 && !isString(record.cancellation_reason)) {
859
+ return null;
860
+ }
861
+ if (record.cleanup_reason !== void 0 && !isString(record.cleanup_reason)) {
862
+ return null;
863
+ }
864
+ return record;
865
+ };
866
+ var readTaskFile = async (filePath) => {
867
+ try {
868
+ const raw = await fs5.readFile(filePath, "utf8");
869
+ return normalizeTaskRecord(JSON.parse(raw));
870
+ } catch {
871
+ return null;
872
+ }
873
+ };
874
+ var taskFileName = (taskId) => `${encodeURIComponent(taskId)}.json`;
875
+ var TaskRegistryStore = class {
876
+ tasksDir;
877
+ constructor(tasksDir) {
878
+ if (tasksDir) {
879
+ this.tasksDir = tasksDir;
880
+ return;
881
+ }
882
+ const root = resolveStoragePaths().root;
883
+ this.tasksDir = path5.join(root, TASKS_DIRNAME);
884
+ }
885
+ async ensureDir() {
886
+ await fs5.mkdir(this.tasksDir, { recursive: true });
887
+ }
888
+ taskPath(taskId) {
889
+ return path5.join(this.tasksDir, taskFileName(taskId));
890
+ }
891
+ async list() {
892
+ await this.ensureDir();
893
+ const entries = await fs5.readdir(this.tasksDir, { withFileTypes: true });
894
+ const tasks = (await Promise.all(
895
+ entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path5.join(this.tasksDir, entry.name)))
896
+ )).filter((task) => task !== null);
897
+ const keyBackfills = assignMissingShellKeys(tasks);
898
+ if (keyBackfills.length > 0) {
899
+ await Promise.all(keyBackfills.map(({ next }) => this.upsert(next)));
900
+ const byId = new Map(keyBackfills.map(({ next }) => [next.task_id, next]));
901
+ return sortByUpdatedDesc(tasks.map((task) => byId.get(task.task_id) ?? task));
902
+ }
903
+ return sortByUpdatedDesc(tasks);
904
+ }
905
+ async get(taskId) {
906
+ const tasks = await this.list();
907
+ return tasks.find((task) => task.task_id === taskId) ?? null;
908
+ }
909
+ async upsert(record) {
910
+ await this.ensureDir();
911
+ await atomicWrite(
912
+ this.taskPath(record.task_id),
913
+ `${JSON.stringify(record, null, 2)}
914
+ `
915
+ );
916
+ }
917
+ async patch(taskId, patch) {
918
+ const current = await this.get(taskId);
919
+ if (!current) return null;
920
+ const next = {
921
+ ...current,
922
+ ...patch,
923
+ version: 1,
924
+ task_id: current.task_id,
925
+ created_at: current.created_at
926
+ };
927
+ await this.upsert(next);
928
+ return next;
929
+ }
930
+ };
931
+
932
+ // src/tool-output-cache.ts
933
+ import { promises as fs6 } from "fs";
934
+ import path6 from "path";
729
935
  var DEFAULT_MAX_MATCHES = 50;
730
936
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
731
937
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -829,15 +1035,15 @@ var ToolOutputCacheStoreImpl = class {
829
1035
  async save(record) {
830
1036
  const refId = normalizeRefId(record.tool_call_id);
831
1037
  const filePath = this.resolvePath(refId);
832
- await fs5.mkdir(this.baseDir, { recursive: true });
833
- await fs5.writeFile(filePath, record.content, "utf8");
1038
+ await fs6.mkdir(this.baseDir, { recursive: true });
1039
+ await fs6.writeFile(filePath, record.content, "utf8");
834
1040
  const byteSize = Buffer.byteLength(record.content, "utf8");
835
1041
  const lineCount = record.content.split(/\r?\n/).length;
836
1042
  return { id: refId, byte_size: byteSize, line_count: lineCount };
837
1043
  }
838
1044
  async read(refId, options = {}) {
839
1045
  const filePath = this.resolvePath(refId);
840
- const content = await fs5.readFile(filePath, "utf8");
1046
+ const content = await fs6.readFile(filePath, "utf8");
841
1047
  const lines = content.split(/\r?\n/);
842
1048
  const offset = options.offset ?? 0;
843
1049
  const limit = options.limit ?? lines.length;
@@ -894,9 +1100,21 @@ var ToolOutputCacheStoreImpl = class {
894
1100
  For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).` : ""
895
1101
  );
896
1102
  }
1103
+ async readTail(refId, options) {
1104
+ const filePath = this.resolvePath(refId);
1105
+ const content = await fs6.readFile(filePath, "utf8");
1106
+ const lines = content.split(/\r?\n/);
1107
+ const tailLines = Math.max(1, Math.trunc(options.tail_lines));
1108
+ const start = Math.max(0, lines.length - tailLines);
1109
+ return {
1110
+ content: lines.slice(start).join("\n"),
1111
+ total_lines: lines.length,
1112
+ omitted_lines: start
1113
+ };
1114
+ }
897
1115
  async readLine(refId, options) {
898
1116
  const filePath = this.resolvePath(refId);
899
- const content = await fs5.readFile(filePath, "utf8");
1117
+ const content = await fs6.readFile(filePath, "utf8");
900
1118
  const lines = content.split(/\r?\n/);
901
1119
  const lineIndex = options.line_number - 1;
902
1120
  if (lineIndex < 0 || lineIndex >= lines.length) {
@@ -935,7 +1153,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
935
1153
  }
936
1154
  async grep(refId, options) {
937
1155
  const filePath = this.resolvePath(refId);
938
- const content = await fs5.readFile(filePath, "utf8");
1156
+ const content = await fs6.readFile(filePath, "utf8");
939
1157
  const lines = content.split(/\r?\n/);
940
1158
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
941
1159
  const before = Math.max(0, options.before ?? 0);
@@ -986,7 +1204,7 @@ ${snippet}`;
986
1204
  return output;
987
1205
  }
988
1206
  resolvePath(refId) {
989
- return path5.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1207
+ return path6.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
990
1208
  }
991
1209
  };
992
1210
  export {
@@ -996,6 +1214,7 @@ export {
996
1214
  SessionStateStoreImpl,
997
1215
  SessionStoreWriterImpl,
998
1216
  StoragePathServiceImpl,
1217
+ TaskRegistryStore,
999
1218
  ToolOutputCacheStoreImpl,
1000
1219
  ensureStorageDirs,
1001
1220
  resolveStoragePaths
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/storage",
3
- "version": "0.1.44",
3
+ "version": "0.1.45",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20 <25"
@@ -23,8 +23,8 @@
23
23
  "typecheck": "tsc --noEmit"
24
24
  },
25
25
  "dependencies": {
26
- "@codelia/core": "0.1.44",
27
- "@codelia/shared-types": "0.1.44",
26
+ "@codelia/core": "0.1.45",
27
+ "@codelia/shared-types": "0.1.45",
28
28
  "better-sqlite3": "^12.6.2"
29
29
  },
30
30
  "publishConfig": {