@earendil-works/pi-agent-core 0.75.3 → 0.75.4

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 (71) hide show
  1. package/dist/agent-loop.d.ts +1 -1
  2. package/dist/agent-loop.d.ts.map +1 -1
  3. package/dist/agent-loop.js +23 -0
  4. package/dist/agent-loop.js.map +1 -1
  5. package/dist/agent.d.ts +2 -2
  6. package/dist/agent.d.ts.map +1 -1
  7. package/dist/agent.js +1 -1
  8. package/dist/agent.js.map +1 -1
  9. package/dist/harness/agent-harness.d.ts +2 -2
  10. package/dist/harness/agent-harness.d.ts.map +1 -1
  11. package/dist/harness/agent-harness.js.map +1 -1
  12. package/dist/harness/compaction/branch-summarization.d.ts +5 -5
  13. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
  14. package/dist/harness/compaction/branch-summarization.js.map +1 -1
  15. package/dist/harness/compaction/compaction.d.ts +4 -4
  16. package/dist/harness/compaction/compaction.d.ts.map +1 -1
  17. package/dist/harness/compaction/compaction.js.map +1 -1
  18. package/dist/harness/compaction/utils.d.ts +1 -1
  19. package/dist/harness/compaction/utils.d.ts.map +1 -1
  20. package/dist/harness/compaction/utils.js.map +1 -1
  21. package/dist/harness/env/nodejs.d.ts +1 -1
  22. package/dist/harness/env/nodejs.d.ts.map +1 -1
  23. package/dist/harness/env/nodejs.js +6 -1
  24. package/dist/harness/env/nodejs.js.map +1 -1
  25. package/dist/harness/messages.d.ts +2 -2
  26. package/dist/harness/messages.d.ts.map +1 -1
  27. package/dist/harness/messages.js.map +1 -1
  28. package/dist/harness/prompt-templates.d.ts +1 -1
  29. package/dist/harness/prompt-templates.d.ts.map +1 -1
  30. package/dist/harness/prompt-templates.js.map +1 -1
  31. package/dist/harness/session/jsonl-repo.d.ts +1 -1
  32. package/dist/harness/session/jsonl-repo.d.ts.map +1 -1
  33. package/dist/harness/session/jsonl-repo.js.map +1 -1
  34. package/dist/harness/session/jsonl-storage.d.ts +1 -1
  35. package/dist/harness/session/jsonl-storage.d.ts.map +1 -1
  36. package/dist/harness/session/jsonl-storage.js.map +1 -1
  37. package/dist/harness/session/memory-repo.d.ts +1 -1
  38. package/dist/harness/session/memory-repo.d.ts.map +1 -1
  39. package/dist/harness/session/memory-repo.js.map +1 -1
  40. package/dist/harness/session/memory-storage.d.ts +1 -1
  41. package/dist/harness/session/memory-storage.d.ts.map +1 -1
  42. package/dist/harness/session/memory-storage.js.map +1 -1
  43. package/dist/harness/session/repo-utils.d.ts +2 -2
  44. package/dist/harness/session/repo-utils.d.ts.map +1 -1
  45. package/dist/harness/session/repo-utils.js.map +1 -1
  46. package/dist/harness/session/session.d.ts +2 -2
  47. package/dist/harness/session/session.d.ts.map +1 -1
  48. package/dist/harness/session/session.js.map +1 -1
  49. package/dist/harness/skills.d.ts +1 -1
  50. package/dist/harness/skills.d.ts.map +1 -1
  51. package/dist/harness/skills.js.map +1 -1
  52. package/dist/harness/system-prompt.d.ts +1 -1
  53. package/dist/harness/system-prompt.d.ts.map +1 -1
  54. package/dist/harness/system-prompt.js.map +1 -1
  55. package/dist/harness/types.d.ts +10 -22
  56. package/dist/harness/types.d.ts.map +1 -1
  57. package/dist/harness/types.js +17 -23
  58. package/dist/harness/types.js.map +1 -1
  59. package/dist/harness/utils/shell-output.d.ts +1 -1
  60. package/dist/harness/utils/shell-output.d.ts.map +1 -1
  61. package/dist/harness/utils/shell-output.js.map +1 -1
  62. package/dist/harness/utils/truncate.d.ts.map +1 -1
  63. package/dist/harness/utils/truncate.js +2 -0
  64. package/dist/harness/utils/truncate.js.map +1 -1
  65. package/dist/index.d.ts +19 -19
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/node.d.ts +2 -2
  69. package/dist/node.d.ts.map +1 -1
  70. package/dist/node.js.map +1 -1
  71. package/package.json +9 -10
@@ -1 +1 @@
1
- {"version":3,"file":"jsonl-storage.d.ts","sourceRoot":"","sources":["../../../src/harness/session/json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I,OAAO,CAAC,MAAM,CAAC,CAErC;IAEK,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CASxD;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEhE;IAEK,WAAW,CAAC,KAAK,SAAS,gBAAgB,CAAC,MAAM,CAAC,EACvD,IAAI,EAAE,KAAK,GACT,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE;QAAE,IAAI,EAAE,KAAK,CAAA;KAAE,CAAC,CAAC,CAAC,CAE5D;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEtD;IAEK,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAatE;IAEK,UAAU,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAE9C;CACD","sourcesContent":["import type { FileSystem, JsonlSessionMetadata, LeafEntry, SessionStorage, SessionTreeEntry } from \"../types.js\";\nimport { SessionError, toError } from \"../types.js\";\nimport { getFileSystemResultOrThrow } from \"./repo-utils.js\";\nimport { uuidv7 } from \"./uuid.js\";\n\ntype JsonlSessionStorageFileSystem = Pick<FileSystem, \"readTextFile\" | \"readTextLines\" | \"writeFile\" | \"appendFile\">;\n\ninterface SessionHeader {\n\ttype: \"session\";\n\tversion: 3;\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n}\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction invalidSession(filePath: string, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\"invalid_session\", `Invalid JSONL session file ${filePath}: ${message}`, cause);\n}\n\nfunction invalidEntry(filePath: string, lineNumber: number, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\n\t\t\"invalid_entry\",\n\t\t`Invalid JSONL session file ${filePath}: line ${lineNumber} ${message}`,\n\t\tcause,\n\t);\n}\n\nfunction parseHeaderLine(line: string, filePath: string): SessionHeader {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidSession(filePath, \"first line is not a valid session header\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.type !== \"session\") throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.version !== 3) throw invalidSession(filePath, \"unsupported session version\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidSession(filePath, \"session header is missing id\");\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidSession(filePath, \"session header is missing timestamp\");\n\t}\n\tif (typeof parsed.cwd !== \"string\" || !parsed.cwd) throw invalidSession(filePath, \"session header is missing cwd\");\n\tif (parsed.parentSession !== undefined && typeof parsed.parentSession !== \"string\") {\n\t\tthrow invalidSession(filePath, \"session header parentSession must be a string\");\n\t}\n\treturn {\n\t\ttype: \"session\",\n\t\tversion: 3,\n\t\tid: parsed.id,\n\t\ttimestamp: parsed.timestamp,\n\t\tcwd: parsed.cwd,\n\t\tparentSession: parsed.parentSession,\n\t};\n}\n\nfunction parseEntryLine(line: string, filePath: string, lineNumber: number): SessionTreeEntry {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is not valid JSON\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidEntry(filePath, lineNumber, \"is not a valid session entry\");\n\tif (typeof parsed.type !== \"string\") throw invalidEntry(filePath, lineNumber, \"is missing entry type\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidEntry(filePath, lineNumber, \"is missing entry id\");\n\tif (parsed.parentId !== null && typeof parsed.parentId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid parentId\");\n\t}\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is missing timestamp\");\n\t}\n\tif (parsed.type === \"leaf\" && parsed.targetId !== null && typeof parsed.targetId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid targetId\");\n\t}\n\treturn parsed as unknown as SessionTreeEntry;\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nfunction headerToSessionMetadata(header: SessionHeader, path: string): JsonlSessionMetadata {\n\treturn {\n\t\tid: header.id,\n\t\tcreatedAt: header.timestamp,\n\t\tcwd: header.cwd,\n\t\tpath,\n\t\tparentSessionPath: header.parentSession,\n\t};\n}\n\nexport async function loadJsonlSessionMetadata(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<JsonlSessionMetadata> {\n\tconst lines = getFileSystemResultOrThrow(\n\t\tawait fs.readTextLines(filePath, { maxLines: 1 }),\n\t\t`Failed to read session header ${filePath}`,\n\t);\n\tconst line = lines[0];\n\tif (line?.trim()) return headerToSessionMetadata(parseHeaderLine(line, filePath), filePath);\n\tthrow invalidSession(filePath, \"missing session header\");\n}\n\nasync function loadJsonlStorage(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<{\n\theader: SessionHeader;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n}> {\n\tconst content = getFileSystemResultOrThrow(await fs.readTextFile(filePath), `Failed to read session ${filePath}`);\n\tconst lines = content.split(\"\\n\").filter((line) => line.trim());\n\tif (lines.length === 0) {\n\t\tthrow invalidSession(filePath, \"missing session header\");\n\t}\n\n\tconst header = parseHeaderLine(lines[0]!, filePath);\n\tconst entries: SessionTreeEntry[] = [];\n\tlet leafId: string | null = null;\n\tfor (let i = 1; i < lines.length; i++) {\n\t\tconst entry = parseEntryLine(lines[i]!, filePath, i + 1);\n\t\tentries.push(entry);\n\t\tleafId = leafIdAfterEntry(entry);\n\t}\n\treturn { header, entries, leafId };\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionStorageFileSystem;\n\tprivate readonly filePath: string;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate currentLeafId: string | null;\n\n\tprivate constructor(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\theader: SessionHeader,\n\t\tentries: SessionTreeEntry[],\n\t\tleafId: string | null,\n\t) {\n\t\tthis.fs = fs;\n\t\tthis.filePath = filePath;\n\t\tthis.metadata = headerToSessionMetadata(header, this.filePath);\n\t\tthis.entries = entries;\n\t\tthis.byId = new Map(entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(entries);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tstatic async open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionStorage> {\n\t\tconst loaded = await loadJsonlStorage(fs, filePath);\n\t\treturn new JsonlSessionStorage(fs, filePath, loaded.header, loaded.entries, loaded.leafId);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\toptions: {\n\t\t\tcwd: string;\n\t\t\tsessionId: string;\n\t\t\tparentSessionPath?: string;\n\t\t},\n\t): Promise<JsonlSessionStorage> {\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: 3,\n\t\t\tid: options.sessionId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: options.cwd,\n\t\t\tparentSession: options.parentSessionPath,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait fs.writeFile(filePath, `${JSON.stringify(header)}\\n`),\n\t\t\t`Failed to create session ${filePath}`,\n\t\t);\n\t\treturn new JsonlSessionStorage(fs, filePath, header, [], null);\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.currentLeafId !== null && !this.byId.has(this.currentLeafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.currentLeafId} not found`);\n\t\t}\n\t\treturn this.currentLeafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.currentLeafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session leaf ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session entry ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.currentLeafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
1
+ {"version":3,"file":"jsonl-storage.d.ts","sourceRoot":"","sources":["../../../src/harness/session/jsonl-storage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,oBAAoB,EAAa,cAAc,EAAE,gBAAgB,EAA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C,CASxD;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEhE;IAEK,WAAW,CAAC,KAAK,SAAS,gBAAgB,CAAC,MAAM,CAAC,EACvD,IAAI,EAAE,KAAK,GACT,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE;QAAE,IAAI,EAAE,KAAK,CAAA;KAAE,CAAC,CAAC,CAAC,CAE5D;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEtD;IAEK,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAatE;IAEK,UAAU,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAE9C;CACD","sourcesContent":["import type { FileSystem, JsonlSessionMetadata, LeafEntry, SessionStorage, SessionTreeEntry } from \"../types.ts\";\nimport { SessionError, toError } from \"../types.ts\";\nimport { getFileSystemResultOrThrow } from \"./repo-utils.ts\";\nimport { uuidv7 } from \"./uuid.ts\";\n\ntype JsonlSessionStorageFileSystem = Pick<FileSystem, \"readTextFile\" | \"readTextLines\" | \"writeFile\" | \"appendFile\">;\n\ninterface SessionHeader {\n\ttype: \"session\";\n\tversion: 3;\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n}\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction invalidSession(filePath: string, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\"invalid_session\", `Invalid JSONL session file ${filePath}: ${message}`, cause);\n}\n\nfunction invalidEntry(filePath: string, lineNumber: number, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\n\t\t\"invalid_entry\",\n\t\t`Invalid JSONL session file ${filePath}: line ${lineNumber} ${message}`,\n\t\tcause,\n\t);\n}\n\nfunction parseHeaderLine(line: string, filePath: string): SessionHeader {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidSession(filePath, \"first line is not a valid session header\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.type !== \"session\") throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.version !== 3) throw invalidSession(filePath, \"unsupported session version\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidSession(filePath, \"session header is missing id\");\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidSession(filePath, \"session header is missing timestamp\");\n\t}\n\tif (typeof parsed.cwd !== \"string\" || !parsed.cwd) throw invalidSession(filePath, \"session header is missing cwd\");\n\tif (parsed.parentSession !== undefined && typeof parsed.parentSession !== \"string\") {\n\t\tthrow invalidSession(filePath, \"session header parentSession must be a string\");\n\t}\n\treturn {\n\t\ttype: \"session\",\n\t\tversion: 3,\n\t\tid: parsed.id,\n\t\ttimestamp: parsed.timestamp,\n\t\tcwd: parsed.cwd,\n\t\tparentSession: parsed.parentSession,\n\t};\n}\n\nfunction parseEntryLine(line: string, filePath: string, lineNumber: number): SessionTreeEntry {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is not valid JSON\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidEntry(filePath, lineNumber, \"is not a valid session entry\");\n\tif (typeof parsed.type !== \"string\") throw invalidEntry(filePath, lineNumber, \"is missing entry type\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidEntry(filePath, lineNumber, \"is missing entry id\");\n\tif (parsed.parentId !== null && typeof parsed.parentId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid parentId\");\n\t}\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is missing timestamp\");\n\t}\n\tif (parsed.type === \"leaf\" && parsed.targetId !== null && typeof parsed.targetId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid targetId\");\n\t}\n\treturn parsed as unknown as SessionTreeEntry;\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nfunction headerToSessionMetadata(header: SessionHeader, path: string): JsonlSessionMetadata {\n\treturn {\n\t\tid: header.id,\n\t\tcreatedAt: header.timestamp,\n\t\tcwd: header.cwd,\n\t\tpath,\n\t\tparentSessionPath: header.parentSession,\n\t};\n}\n\nexport async function loadJsonlSessionMetadata(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<JsonlSessionMetadata> {\n\tconst lines = getFileSystemResultOrThrow(\n\t\tawait fs.readTextLines(filePath, { maxLines: 1 }),\n\t\t`Failed to read session header ${filePath}`,\n\t);\n\tconst line = lines[0];\n\tif (line?.trim()) return headerToSessionMetadata(parseHeaderLine(line, filePath), filePath);\n\tthrow invalidSession(filePath, \"missing session header\");\n}\n\nasync function loadJsonlStorage(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<{\n\theader: SessionHeader;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n}> {\n\tconst content = getFileSystemResultOrThrow(await fs.readTextFile(filePath), `Failed to read session ${filePath}`);\n\tconst lines = content.split(\"\\n\").filter((line) => line.trim());\n\tif (lines.length === 0) {\n\t\tthrow invalidSession(filePath, \"missing session header\");\n\t}\n\n\tconst header = parseHeaderLine(lines[0]!, filePath);\n\tconst entries: SessionTreeEntry[] = [];\n\tlet leafId: string | null = null;\n\tfor (let i = 1; i < lines.length; i++) {\n\t\tconst entry = parseEntryLine(lines[i]!, filePath, i + 1);\n\t\tentries.push(entry);\n\t\tleafId = leafIdAfterEntry(entry);\n\t}\n\treturn { header, entries, leafId };\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionStorageFileSystem;\n\tprivate readonly filePath: string;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate currentLeafId: string | null;\n\n\tprivate constructor(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\theader: SessionHeader,\n\t\tentries: SessionTreeEntry[],\n\t\tleafId: string | null,\n\t) {\n\t\tthis.fs = fs;\n\t\tthis.filePath = filePath;\n\t\tthis.metadata = headerToSessionMetadata(header, this.filePath);\n\t\tthis.entries = entries;\n\t\tthis.byId = new Map(entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(entries);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tstatic async open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionStorage> {\n\t\tconst loaded = await loadJsonlStorage(fs, filePath);\n\t\treturn new JsonlSessionStorage(fs, filePath, loaded.header, loaded.entries, loaded.leafId);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\toptions: {\n\t\t\tcwd: string;\n\t\t\tsessionId: string;\n\t\t\tparentSessionPath?: string;\n\t\t},\n\t): Promise<JsonlSessionStorage> {\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: 3,\n\t\t\tid: options.sessionId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: options.cwd,\n\t\t\tparentSession: options.parentSessionPath,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait fs.writeFile(filePath, `${JSON.stringify(header)}\\n`),\n\t\t\t`Failed to create session ${filePath}`,\n\t\t);\n\t\treturn new JsonlSessionStorage(fs, filePath, header, [], null);\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.currentLeafId !== null && !this.byId.has(this.currentLeafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.currentLeafId} not found`);\n\t\t}\n\t\treturn this.currentLeafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.currentLeafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session leaf ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session entry ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.currentLeafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonl-storage.js","sourceRoot":"","sources":["../../../src/harness/session/jsonl-storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAA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AAA,CAChH;IAED,KAAK,CAAC,QAAQ,CAAC,EAAU,EAA+B;QACvD,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAAA,CAC/B;IAED,KAAK,CAAC,aAAa,CAAC,MAAqB,EAA+B;QACvE,IAAI,MAAM,KAAK,IAAI;YAAE,OAAO,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAuB,EAAE,CAAC;QACpC,IAAI,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACpC,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,SAAS,MAAM,YAAY,CAAC,CAAC;QAC/E,OAAO,OAAO,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACtB,IAAI,CAAC,OAAO,CAAC,QAAQ;gBAAE,MAAM;YAC7B,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAC/C,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,YAAY,CAAC,iBAAiB,EAAE,SAAS,OAAO,CAAC,QAAQ,YAAY,CAAC,CAAC;YAC9F,OAAO,GAAG,MAAM,CAAC;QAClB,CAAC;QACD,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,KAAK,CAAC,UAAU,GAAgC;QAC/C,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAAA,CACzB;CACD","sourcesContent":["import type { FileSystem, JsonlSessionMetadata, LeafEntry, SessionStorage, SessionTreeEntry } from \"../types.js\";\nimport { SessionError, toError } from \"../types.js\";\nimport { getFileSystemResultOrThrow } from \"./repo-utils.js\";\nimport { uuidv7 } from \"./uuid.js\";\n\ntype JsonlSessionStorageFileSystem = Pick<FileSystem, \"readTextFile\" | \"readTextLines\" | \"writeFile\" | \"appendFile\">;\n\ninterface SessionHeader {\n\ttype: \"session\";\n\tversion: 3;\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n}\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction invalidSession(filePath: string, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\"invalid_session\", `Invalid JSONL session file ${filePath}: ${message}`, cause);\n}\n\nfunction invalidEntry(filePath: string, lineNumber: number, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\n\t\t\"invalid_entry\",\n\t\t`Invalid JSONL session file ${filePath}: line ${lineNumber} ${message}`,\n\t\tcause,\n\t);\n}\n\nfunction parseHeaderLine(line: string, filePath: string): SessionHeader {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidSession(filePath, \"first line is not a valid session header\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.type !== \"session\") throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.version !== 3) throw invalidSession(filePath, \"unsupported session version\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidSession(filePath, \"session header is missing id\");\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidSession(filePath, \"session header is missing timestamp\");\n\t}\n\tif (typeof parsed.cwd !== \"string\" || !parsed.cwd) throw invalidSession(filePath, \"session header is missing cwd\");\n\tif (parsed.parentSession !== undefined && typeof parsed.parentSession !== \"string\") {\n\t\tthrow invalidSession(filePath, \"session header parentSession must be a string\");\n\t}\n\treturn {\n\t\ttype: \"session\",\n\t\tversion: 3,\n\t\tid: parsed.id,\n\t\ttimestamp: parsed.timestamp,\n\t\tcwd: parsed.cwd,\n\t\tparentSession: parsed.parentSession,\n\t};\n}\n\nfunction parseEntryLine(line: string, filePath: string, lineNumber: number): SessionTreeEntry {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is not valid JSON\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidEntry(filePath, lineNumber, \"is not a valid session entry\");\n\tif (typeof parsed.type !== \"string\") throw invalidEntry(filePath, lineNumber, \"is missing entry type\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidEntry(filePath, lineNumber, \"is missing entry id\");\n\tif (parsed.parentId !== null && typeof parsed.parentId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid parentId\");\n\t}\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is missing timestamp\");\n\t}\n\tif (parsed.type === \"leaf\" && parsed.targetId !== null && typeof parsed.targetId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid targetId\");\n\t}\n\treturn parsed as unknown as SessionTreeEntry;\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nfunction headerToSessionMetadata(header: SessionHeader, path: string): JsonlSessionMetadata {\n\treturn {\n\t\tid: header.id,\n\t\tcreatedAt: header.timestamp,\n\t\tcwd: header.cwd,\n\t\tpath,\n\t\tparentSessionPath: header.parentSession,\n\t};\n}\n\nexport async function loadJsonlSessionMetadata(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<JsonlSessionMetadata> {\n\tconst lines = getFileSystemResultOrThrow(\n\t\tawait fs.readTextLines(filePath, { maxLines: 1 }),\n\t\t`Failed to read session header ${filePath}`,\n\t);\n\tconst line = lines[0];\n\tif (line?.trim()) return headerToSessionMetadata(parseHeaderLine(line, filePath), filePath);\n\tthrow invalidSession(filePath, \"missing session header\");\n}\n\nasync function loadJsonlStorage(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<{\n\theader: SessionHeader;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n}> {\n\tconst content = getFileSystemResultOrThrow(await fs.readTextFile(filePath), `Failed to read session ${filePath}`);\n\tconst lines = content.split(\"\\n\").filter((line) => line.trim());\n\tif (lines.length === 0) {\n\t\tthrow invalidSession(filePath, \"missing session header\");\n\t}\n\n\tconst header = parseHeaderLine(lines[0]!, filePath);\n\tconst entries: SessionTreeEntry[] = [];\n\tlet leafId: string | null = null;\n\tfor (let i = 1; i < lines.length; i++) {\n\t\tconst entry = parseEntryLine(lines[i]!, filePath, i + 1);\n\t\tentries.push(entry);\n\t\tleafId = leafIdAfterEntry(entry);\n\t}\n\treturn { header, entries, leafId };\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionStorageFileSystem;\n\tprivate readonly filePath: string;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate currentLeafId: string | null;\n\n\tprivate constructor(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\theader: SessionHeader,\n\t\tentries: SessionTreeEntry[],\n\t\tleafId: string | null,\n\t) {\n\t\tthis.fs = fs;\n\t\tthis.filePath = filePath;\n\t\tthis.metadata = headerToSessionMetadata(header, this.filePath);\n\t\tthis.entries = entries;\n\t\tthis.byId = new Map(entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(entries);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tstatic async open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionStorage> {\n\t\tconst loaded = await loadJsonlStorage(fs, filePath);\n\t\treturn new JsonlSessionStorage(fs, filePath, loaded.header, loaded.entries, loaded.leafId);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\toptions: {\n\t\t\tcwd: string;\n\t\t\tsessionId: string;\n\t\t\tparentSessionPath?: string;\n\t\t},\n\t): Promise<JsonlSessionStorage> {\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: 3,\n\t\t\tid: options.sessionId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: options.cwd,\n\t\t\tparentSession: options.parentSessionPath,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait fs.writeFile(filePath, `${JSON.stringify(header)}\\n`),\n\t\t\t`Failed to create session ${filePath}`,\n\t\t);\n\t\treturn new JsonlSessionStorage(fs, filePath, header, [], null);\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.currentLeafId !== null && !this.byId.has(this.currentLeafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.currentLeafId} not found`);\n\t\t}\n\t\treturn this.currentLeafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.currentLeafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session leaf ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session entry ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.currentLeafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
1
+ {"version":3,"file":"jsonl-storage.js","sourceRoot":"","sources":["../../../src/harness/session/jsonl-storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAanC,SAAS,gBAAgB,CAAC,UAA+B,EAAE,KAAuB,EAAQ;IACzF,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO;IACnC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;IAClC,IAAI,KAAK,EAAE,CAAC;QACX,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;SAAM,CAAC;QACP,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC;AAAA,CACD;AAED,SAAS,eAAe,CAAC,OAA2B,EAAuB;IAC1E,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC7C,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,gBAAgB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,UAAU,CAAC;AAAA,CAClB;AAED,SAAS,eAAe,CAAC,IAAkC,EAAU;IACpE,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC9B,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAA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ACD,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,KAAK,CAAC,UAAU,GAAgC;QAC/C,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAAA,CACzB;CACD","sourcesContent":["import type { FileSystem, JsonlSessionMetadata, LeafEntry, SessionStorage, SessionTreeEntry } from \"../types.ts\";\nimport { SessionError, toError } from \"../types.ts\";\nimport { getFileSystemResultOrThrow } from \"./repo-utils.ts\";\nimport { uuidv7 } from \"./uuid.ts\";\n\ntype JsonlSessionStorageFileSystem = Pick<FileSystem, \"readTextFile\" | \"readTextLines\" | \"writeFile\" | \"appendFile\">;\n\ninterface SessionHeader {\n\ttype: \"session\";\n\tversion: 3;\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n}\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction invalidSession(filePath: string, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\"invalid_session\", `Invalid JSONL session file ${filePath}: ${message}`, cause);\n}\n\nfunction invalidEntry(filePath: string, lineNumber: number, message: string, cause?: Error): SessionError {\n\treturn new SessionError(\n\t\t\"invalid_entry\",\n\t\t`Invalid JSONL session file ${filePath}: line ${lineNumber} ${message}`,\n\t\tcause,\n\t);\n}\n\nfunction parseHeaderLine(line: string, filePath: string): SessionHeader {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidSession(filePath, \"first line is not a valid session header\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.type !== \"session\") throw invalidSession(filePath, \"first line is not a valid session header\");\n\tif (parsed.version !== 3) throw invalidSession(filePath, \"unsupported session version\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidSession(filePath, \"session header is missing id\");\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidSession(filePath, \"session header is missing timestamp\");\n\t}\n\tif (typeof parsed.cwd !== \"string\" || !parsed.cwd) throw invalidSession(filePath, \"session header is missing cwd\");\n\tif (parsed.parentSession !== undefined && typeof parsed.parentSession !== \"string\") {\n\t\tthrow invalidSession(filePath, \"session header parentSession must be a string\");\n\t}\n\treturn {\n\t\ttype: \"session\",\n\t\tversion: 3,\n\t\tid: parsed.id,\n\t\ttimestamp: parsed.timestamp,\n\t\tcwd: parsed.cwd,\n\t\tparentSession: parsed.parentSession,\n\t};\n}\n\nfunction parseEntryLine(line: string, filePath: string, lineNumber: number): SessionTreeEntry {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(line);\n\t} catch (error) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is not valid JSON\", toError(error));\n\t}\n\tif (!isRecord(parsed)) throw invalidEntry(filePath, lineNumber, \"is not a valid session entry\");\n\tif (typeof parsed.type !== \"string\") throw invalidEntry(filePath, lineNumber, \"is missing entry type\");\n\tif (typeof parsed.id !== \"string\" || !parsed.id) throw invalidEntry(filePath, lineNumber, \"is missing entry id\");\n\tif (parsed.parentId !== null && typeof parsed.parentId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid parentId\");\n\t}\n\tif (typeof parsed.timestamp !== \"string\" || !parsed.timestamp) {\n\t\tthrow invalidEntry(filePath, lineNumber, \"is missing timestamp\");\n\t}\n\tif (parsed.type === \"leaf\" && parsed.targetId !== null && typeof parsed.targetId !== \"string\") {\n\t\tthrow invalidEntry(filePath, lineNumber, \"has invalid targetId\");\n\t}\n\treturn parsed as unknown as SessionTreeEntry;\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nfunction headerToSessionMetadata(header: SessionHeader, path: string): JsonlSessionMetadata {\n\treturn {\n\t\tid: header.id,\n\t\tcreatedAt: header.timestamp,\n\t\tcwd: header.cwd,\n\t\tpath,\n\t\tparentSessionPath: header.parentSession,\n\t};\n}\n\nexport async function loadJsonlSessionMetadata(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<JsonlSessionMetadata> {\n\tconst lines = getFileSystemResultOrThrow(\n\t\tawait fs.readTextLines(filePath, { maxLines: 1 }),\n\t\t`Failed to read session header ${filePath}`,\n\t);\n\tconst line = lines[0];\n\tif (line?.trim()) return headerToSessionMetadata(parseHeaderLine(line, filePath), filePath);\n\tthrow invalidSession(filePath, \"missing session header\");\n}\n\nasync function loadJsonlStorage(\n\tfs: JsonlSessionStorageFileSystem,\n\tfilePath: string,\n): Promise<{\n\theader: SessionHeader;\n\tentries: SessionTreeEntry[];\n\tleafId: string | null;\n}> {\n\tconst content = getFileSystemResultOrThrow(await fs.readTextFile(filePath), `Failed to read session ${filePath}`);\n\tconst lines = content.split(\"\\n\").filter((line) => line.trim());\n\tif (lines.length === 0) {\n\t\tthrow invalidSession(filePath, \"missing session header\");\n\t}\n\n\tconst header = parseHeaderLine(lines[0]!, filePath);\n\tconst entries: SessionTreeEntry[] = [];\n\tlet leafId: string | null = null;\n\tfor (let i = 1; i < lines.length; i++) {\n\t\tconst entry = parseEntryLine(lines[i]!, filePath, i + 1);\n\t\tentries.push(entry);\n\t\tleafId = leafIdAfterEntry(entry);\n\t}\n\treturn { header, entries, leafId };\n}\n\nexport class JsonlSessionStorage implements SessionStorage<JsonlSessionMetadata> {\n\tprivate readonly fs: JsonlSessionStorageFileSystem;\n\tprivate readonly filePath: string;\n\tprivate readonly metadata: JsonlSessionMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate currentLeafId: string | null;\n\n\tprivate constructor(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\theader: SessionHeader,\n\t\tentries: SessionTreeEntry[],\n\t\tleafId: string | null,\n\t) {\n\t\tthis.fs = fs;\n\t\tthis.filePath = filePath;\n\t\tthis.metadata = headerToSessionMetadata(header, this.filePath);\n\t\tthis.entries = entries;\n\t\tthis.byId = new Map(entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(entries);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tstatic async open(fs: JsonlSessionStorageFileSystem, filePath: string): Promise<JsonlSessionStorage> {\n\t\tconst loaded = await loadJsonlStorage(fs, filePath);\n\t\treturn new JsonlSessionStorage(fs, filePath, loaded.header, loaded.entries, loaded.leafId);\n\t}\n\n\tstatic async create(\n\t\tfs: JsonlSessionStorageFileSystem,\n\t\tfilePath: string,\n\t\toptions: {\n\t\t\tcwd: string;\n\t\t\tsessionId: string;\n\t\t\tparentSessionPath?: string;\n\t\t},\n\t): Promise<JsonlSessionStorage> {\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: 3,\n\t\t\tid: options.sessionId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: options.cwd,\n\t\t\tparentSession: options.parentSessionPath,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait fs.writeFile(filePath, `${JSON.stringify(header)}\\n`),\n\t\t\t`Failed to create session ${filePath}`,\n\t\t);\n\t\treturn new JsonlSessionStorage(fs, filePath, header, [], null);\n\t}\n\n\tasync getMetadata(): Promise<JsonlSessionMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.currentLeafId !== null && !this.byId.has(this.currentLeafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.currentLeafId} not found`);\n\t\t}\n\t\treturn this.currentLeafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.currentLeafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session leaf ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.currentLeafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tgetFileSystemResultOrThrow(\n\t\t\tawait this.fs.appendFile(this.filePath, `${JSON.stringify(entry)}\\n`),\n\t\t\t`Failed to append session entry ${entry.id}`,\n\t\t);\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.currentLeafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type Session, type SessionMetadata, type SessionRepo } from "../types.js";
1
+ import { type Session, type SessionMetadata, type SessionRepo } from "../types.ts";
2
2
  export declare class InMemorySessionRepo implements SessionRepo<SessionMetadata, {
3
3
  id?: string;
4
4
  }, void> {
@@ -1 +1 @@
1
- {"version":3,"file":"memory-repo.d.ts","sourceRoot":"","sources":["../../../src/harness/session/memory-repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAIjG,qBAAa,mBAAoB,YAAW,WAAW,CAAC,eAAe,EAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,IAAI,CAAC;IAC9F,OAAO,CAAC,QAAQ,CAA+C;IAEzD,MAAM,CAAC,OAAO,GAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAS7E;IAEK,IAAI,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAMvE;IAEK,IAAI,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC,CAEvC;IAEK,MAAM,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAErD;IAEK,IAAI,CACT,cAAc,EAAE,eAAe,EAC/B,OAAO,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,GACpE,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAWnC;CACD","sourcesContent":["import { type Session, SessionError, type SessionMetadata, type SessionRepo } from \"../types.js\";\nimport { InMemorySessionStorage } from \"./memory-storage.js\";\nimport { createSessionId, createTimestamp, getEntriesToFork, toSession } from \"./repo-utils.js\";\n\nexport class InMemorySessionRepo implements SessionRepo<SessionMetadata, { id?: string }, void> {\n\tprivate sessions = new Map<string, Session<SessionMetadata>>();\n\n\tasync create(options: { id?: string } = {}): Promise<Session<SessionMetadata>> {\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n\n\tasync open(metadata: SessionMetadata): Promise<Session<SessionMetadata>> {\n\t\tconst session = this.sessions.get(metadata.id);\n\t\tif (!session) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t\t}\n\t\treturn session;\n\t}\n\n\tasync list(): Promise<SessionMetadata[]> {\n\t\treturn Promise.all([...this.sessions.values()].map((session) => session.getMetadata()));\n\t}\n\n\tasync delete(metadata: SessionMetadata): Promise<void> {\n\t\tthis.sessions.delete(metadata.id);\n\t}\n\n\tasync fork(\n\t\tsourceMetadata: SessionMetadata,\n\t\toptions: { entryId?: string; position?: \"before\" | \"at\"; id?: string },\n\t): Promise<Session<SessionMetadata>> {\n\t\tconst source = await this.open(sourceMetadata);\n\t\tconst forkedEntries = await getEntriesToFork(source.getStorage(), options);\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata, entries: forkedEntries });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-repo.d.ts","sourceRoot":"","sources":["../../../src/harness/session/memory-repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAIjG,qBAAa,mBAAoB,YAAW,WAAW,CAAC,eAAe,EAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,IAAI,CAAC;IAC9F,OAAO,CAAC,QAAQ,CAA+C;IAEzD,MAAM,CAAC,OAAO,GAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAS7E;IAEK,IAAI,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAMvE;IAEK,IAAI,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC,CAEvC;IAEK,MAAM,CAAC,QAAQ,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAErD;IAEK,IAAI,CACT,cAAc,EAAE,eAAe,EAC/B,OAAO,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,GACpE,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAWnC;CACD","sourcesContent":["import { type Session, SessionError, type SessionMetadata, type SessionRepo } from \"../types.ts\";\nimport { InMemorySessionStorage } from \"./memory-storage.ts\";\nimport { createSessionId, createTimestamp, getEntriesToFork, toSession } from \"./repo-utils.ts\";\n\nexport class InMemorySessionRepo implements SessionRepo<SessionMetadata, { id?: string }, void> {\n\tprivate sessions = new Map<string, Session<SessionMetadata>>();\n\n\tasync create(options: { id?: string } = {}): Promise<Session<SessionMetadata>> {\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n\n\tasync open(metadata: SessionMetadata): Promise<Session<SessionMetadata>> {\n\t\tconst session = this.sessions.get(metadata.id);\n\t\tif (!session) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t\t}\n\t\treturn session;\n\t}\n\n\tasync list(): Promise<SessionMetadata[]> {\n\t\treturn Promise.all([...this.sessions.values()].map((session) => session.getMetadata()));\n\t}\n\n\tasync delete(metadata: SessionMetadata): Promise<void> {\n\t\tthis.sessions.delete(metadata.id);\n\t}\n\n\tasync fork(\n\t\tsourceMetadata: SessionMetadata,\n\t\toptions: { entryId?: string; position?: \"before\" | \"at\"; id?: string },\n\t): Promise<Session<SessionMetadata>> {\n\t\tconst source = await this.open(sourceMetadata);\n\t\tconst forkedEntries = await getEntriesToFork(source.getStorage(), options);\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata, entries: forkedEntries });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn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,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;IAAA,CACxF;IAED,KAAK,CAAC,MAAM,CAAC,QAAyB,EAAiB;QACtD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAAA,CAClC;IAED,KAAK,CAAC,IAAI,CACT,cAA+B,EAC/B,OAAsE,EAClC;QACpC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC/C,MAAM,aAAa,GAAG,MAAM,gBAAgB,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,OAAO,CAAC,CAAC;QAC3E,MAAM,QAAQ,GAAoB;YACjC,EAAE,EAAE,OAAO,CAAC,EAAE,IAAI,eAAe,EAAE;YACnC,SAAS,EAAE,eAAe,EAAE;SAC5B,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,sBAAsB,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC,CAAC;QACjF,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACxC,OAAO,OAAO,CAAC;IAAA,CACf;CACD","sourcesContent":["import { type Session, SessionError, type SessionMetadata, type SessionRepo } from \"../types.js\";\nimport { InMemorySessionStorage } from \"./memory-storage.js\";\nimport { createSessionId, createTimestamp, getEntriesToFork, toSession } from \"./repo-utils.js\";\n\nexport class InMemorySessionRepo implements SessionRepo<SessionMetadata, { id?: string }, void> {\n\tprivate sessions = new Map<string, Session<SessionMetadata>>();\n\n\tasync create(options: { id?: string } = {}): Promise<Session<SessionMetadata>> {\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n\n\tasync open(metadata: SessionMetadata): Promise<Session<SessionMetadata>> {\n\t\tconst session = this.sessions.get(metadata.id);\n\t\tif (!session) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t\t}\n\t\treturn session;\n\t}\n\n\tasync list(): Promise<SessionMetadata[]> {\n\t\treturn Promise.all([...this.sessions.values()].map((session) => session.getMetadata()));\n\t}\n\n\tasync delete(metadata: SessionMetadata): Promise<void> {\n\t\tthis.sessions.delete(metadata.id);\n\t}\n\n\tasync fork(\n\t\tsourceMetadata: SessionMetadata,\n\t\toptions: { entryId?: string; position?: \"before\" | \"at\"; id?: string },\n\t): Promise<Session<SessionMetadata>> {\n\t\tconst source = await this.open(sourceMetadata);\n\t\tconst forkedEntries = await getEntriesToFork(source.getStorage(), options);\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata, entries: forkedEntries });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-repo.js","sourceRoot":"","sources":["../../../src/harness/session/memory-repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,YAAY,EAA0C,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEhG,MAAM,OAAO,mBAAmB;IACvB,QAAQ,GAAG,IAAI,GAAG,EAAoC,CAAC;IAE/D,KAAK,CAAC,MAAM,CAAC,OAAO,GAAoB,EAAE,EAAqC;QAC9E,MAAM,QAAQ,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AAC;QAC3E,MAAM,QAAQ,GAAoB;YACjC,EAAE,EAAE,OAAO,CAAC,EAAE,IAAI,eAAe,EAAE;YACnC,SAAS,EAAE,eAAe,EAAE;SAC5B,CAAC;QACF,MAAM,OAAO,GAAG,IAAI,sBAAsB,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,EAAE,CAAC,CAAC;QACjF,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACxC,OAAO,OAAO,CAAC;IAAA,CACf;CACD","sourcesContent":["import { type Session, SessionError, type SessionMetadata, type SessionRepo } from \"../types.ts\";\nimport { InMemorySessionStorage } from \"./memory-storage.ts\";\nimport { createSessionId, createTimestamp, getEntriesToFork, toSession } from \"./repo-utils.ts\";\n\nexport class InMemorySessionRepo implements SessionRepo<SessionMetadata, { id?: string }, void> {\n\tprivate sessions = new Map<string, Session<SessionMetadata>>();\n\n\tasync create(options: { id?: string } = {}): Promise<Session<SessionMetadata>> {\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n\n\tasync open(metadata: SessionMetadata): Promise<Session<SessionMetadata>> {\n\t\tconst session = this.sessions.get(metadata.id);\n\t\tif (!session) {\n\t\t\tthrow new SessionError(\"not_found\", `Session not found: ${metadata.id}`);\n\t\t}\n\t\treturn session;\n\t}\n\n\tasync list(): Promise<SessionMetadata[]> {\n\t\treturn Promise.all([...this.sessions.values()].map((session) => session.getMetadata()));\n\t}\n\n\tasync delete(metadata: SessionMetadata): Promise<void> {\n\t\tthis.sessions.delete(metadata.id);\n\t}\n\n\tasync fork(\n\t\tsourceMetadata: SessionMetadata,\n\t\toptions: { entryId?: string; position?: \"before\" | \"at\"; id?: string },\n\t): Promise<Session<SessionMetadata>> {\n\t\tconst source = await this.open(sourceMetadata);\n\t\tconst forkedEntries = await getEntriesToFork(source.getStorage(), options);\n\t\tconst metadata: SessionMetadata = {\n\t\t\tid: options.id ?? createSessionId(),\n\t\t\tcreatedAt: createTimestamp(),\n\t\t};\n\t\tconst storage = new InMemorySessionStorage({ metadata, entries: forkedEntries });\n\t\tconst session = toSession(storage);\n\t\tthis.sessions.set(metadata.id, session);\n\t\treturn session;\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type SessionMetadata, type SessionStorage, type SessionTreeEntry } from "../types.js";
1
+ import { type SessionMetadata, type SessionStorage, type SessionTreeEntry } from "../types.ts";
2
2
  export declare class InMemorySessionStorage<TMetadata extends SessionMetadata = SessionMetadata> implements SessionStorage<TMetadata> {
3
3
  private readonly metadata;
4
4
  private entries;
@@ -1 +1 @@
1
- {"version":3,"file":"memory-storage.d.ts","sourceRoot":"","sources":["../../../src/harness/session/memory-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,MAAM,aAAa,CAAC;AAiCrB,qBAAa,sBAAsB,CAAC,SAAS,SAAS,eAAe,GAAG,eAAe,CACtF,YAAW,cAAc,CAAC,SAAS,CAAC;IAEpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAY;IACrC,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,IAAI,CAAgC;IAC5C,OAAO,CAAC,UAAU,CAAsB;IACxC,OAAO,CAAC,MAAM,CAAgB;IAE9B,YAAY,OAAO,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC;QAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;KAAE,EAU3E;IAEK,WAAW,IAAI,OAAO,CAAC,SAAS,CAAC,CAEtC;IAEK,SAAS,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAKxC;IAEK,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAcpD;IAEK,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC,CAErC;IAEK,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAKxD;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEhE;IAEK,WAAW,CAAC,KAAK,SAAS,gBAAgB,CAAC,MAAM,CAAC,EACvD,IAAI,EAAE,KAAK,GACT,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE;QAAE,IAAI,EAAE,KAAK,CAAA;KAAE,CAAC,CAAC,CAAC,CAE5D;IAEK,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEtD;IAEK,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAatE;IAEK,UAAU,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAE9C;CACD","sourcesContent":["import {\n\ttype LeafEntry,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.js\";\nimport { uuidv7 } from \"./uuid.js\";\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nexport class InMemorySessionStorage<TMetadata extends SessionMetadata = SessionMetadata>\n\timplements SessionStorage<TMetadata>\n{\n\tprivate readonly metadata: TMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate leafId: string | null;\n\n\tconstructor(options?: { entries?: SessionTreeEntry[]; metadata?: TMetadata }) {\n\t\tthis.entries = options?.entries ? [...options.entries] : [];\n\t\tthis.byId = new Map(this.entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(this.entries);\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.entries) this.leafId = leafIdAfterEntry(entry);\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\tthis.metadata = options?.metadata ?? ({ id: uuidv7(), createdAt: new Date().toISOString() } as TMetadata);\n\t}\n\n\tasync getMetadata(): Promise<TMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\treturn this.leafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.leafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-storage.d.ts","sourceRoot":"","sources":["../../../src/harness/session/memory-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,gB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O,CAAC,gBAAgB,EAAE,CAAC,CAE9C;CACD","sourcesContent":["import {\n\ttype LeafEntry,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.ts\";\nimport { uuidv7 } from \"./uuid.ts\";\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nexport class InMemorySessionStorage<TMetadata extends SessionMetadata = SessionMetadata>\n\timplements SessionStorage<TMetadata>\n{\n\tprivate readonly metadata: TMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate leafId: string | null;\n\n\tconstructor(options?: { entries?: SessionTreeEntry[]; metadata?: TMetadata }) {\n\t\tthis.entries = options?.entries ? [...options.entries] : [];\n\t\tthis.byId = new Map(this.entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(this.entries);\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.entries) this.leafId = leafIdAfterEntry(entry);\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\tthis.metadata = options?.metadata ?? ({ id: uuidv7(), createdAt: new Date().toISOString() } as TMetadata);\n\t}\n\n\tasync getMetadata(): Promise<TMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\treturn this.leafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.leafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"memory-storage.js","sourceRoot":"","sources":["../../../src/harness/session/memory-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,GAIZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,SAAS,gBAAgB,CAAC,UAA+B,EAAE,KAAuB,EAAQ;IACzF,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO;IACnC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;IAClC,IAAI,KAAK,EAAE,CAAC;QACX,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;SAAM,CAAC;QACP,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC;AAAA,CACD;AAED,SAAS,eAAe,CAAC,OAA2B,EAAuB;IAC1E,MAAM,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC7C,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,gBAAgB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,UAAU,CAAC;AAAA,CAClB;AAED,SAAS,eAAe,CAAC,IAAkC,EAAU;IACpE,KAAK,IAAI,CAAC,GAAG,CA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S,MAAM,YAAY,CAAC,CAAC;QAC/E,OAAO,OAAO,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACtB,IAAI,CAAC,OAAO,CAAC,QAAQ;gBAAE,MAAM;YAC7B,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAC/C,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,YAAY,CAAC,iBAAiB,EAAE,SAAS,OAAO,CAAC,QAAQ,YAAY,CAAC,CAAC;YAC9F,OAAO,GAAG,MAAM,CAAC;QAClB,CAAC;QACD,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,KAAK,CAAC,UAAU,GAAgC;QAC/C,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAAA,CACzB;CACD","sourcesContent":["import {\n\ttype LeafEntry,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.js\";\nimport { uuidv7 } from \"./uuid.js\";\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nexport class InMemorySessionStorage<TMetadata extends SessionMetadata = SessionMetadata>\n\timplements SessionStorage<TMetadata>\n{\n\tprivate readonly metadata: TMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate leafId: string | null;\n\n\tconstructor(options?: { entries?: SessionTreeEntry[]; metadata?: TMetadata }) {\n\t\tthis.entries = options?.entries ? [...options.entries] : [];\n\t\tthis.byId = new Map(this.entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(this.entries);\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.entries) this.leafId = leafIdAfterEntry(entry);\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\tthis.metadata = options?.metadata ?? ({ id: uuidv7(), createdAt: new Date().toISOString() } as TMetadata);\n\t}\n\n\tasync getMetadata(): Promise<TMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\treturn this.leafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.leafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
1
+ {"version":3,"file":"memory-storage.js","sourceRoot":"","sources":["../../../src/harness/session/memory-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,YAAY,GAIZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,SAAS,gBAAgB,CAAC,UAA+B,EAAE,KAAuB,EAAQ;IACzF,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO;IACnC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;IAClC,IAAI,KAAK,EAAE,CA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,KAAK,EAAuD,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;IAAA,CAChH;IAED,KAAK,CAAC,QAAQ,CAAC,EAAU,EAA+B;QACvD,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAAA,CAC/B;IAED,KAAK,CAAC,aAAa,CAAC,MAAqB,EAA+B;QACvE,IAAI,MAAM,KAAK,IAAI;YAAE,OAAO,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAuB,EAAE,CAAC;QACpC,IAAI,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACpC,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,SAAS,MAAM,YAAY,CAAC,CAAC;QAC/E,OAAO,OAAO,EAAE,CAAC;YAChB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YACtB,IAAI,CAAC,OAAO,CAAC,QAAQ;gBAAE,MAAM;YAC7B,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;YAC/C,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,YAAY,CAAC,iBAAiB,EAAE,SAAS,OAAO,CAAC,QAAQ,YAAY,CAAC,CAAC;YAC9F,OAAO,GAAG,MAAM,CAAC;QAClB,CAAC;QACD,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,KAAK,CAAC,UAAU,GAAgC;QAC/C,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAAA,CACzB;CACD","sourcesContent":["import {\n\ttype LeafEntry,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.ts\";\nimport { uuidv7 } from \"./uuid.ts\";\n\nfunction updateLabelCache(labelsById: Map<string, string>, entry: SessionTreeEntry): void {\n\tif (entry.type !== \"label\") return;\n\tconst label = entry.label?.trim();\n\tif (label) {\n\t\tlabelsById.set(entry.targetId, label);\n\t} else {\n\t\tlabelsById.delete(entry.targetId);\n\t}\n}\n\nfunction buildLabelsById(entries: SessionTreeEntry[]): Map<string, string> {\n\tconst labelsById = new Map<string, string>();\n\tfor (const entry of entries) {\n\t\tupdateLabelCache(labelsById, entry);\n\t}\n\treturn labelsById;\n}\n\nfunction generateEntryId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = uuidv7().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\treturn uuidv7();\n}\n\nfunction leafIdAfterEntry(entry: SessionTreeEntry): string | null {\n\treturn entry.type === \"leaf\" ? entry.targetId : entry.id;\n}\n\nexport class InMemorySessionStorage<TMetadata extends SessionMetadata = SessionMetadata>\n\timplements SessionStorage<TMetadata>\n{\n\tprivate readonly metadata: TMetadata;\n\tprivate entries: SessionTreeEntry[];\n\tprivate byId: Map<string, SessionTreeEntry>;\n\tprivate labelsById: Map<string, string>;\n\tprivate leafId: string | null;\n\n\tconstructor(options?: { entries?: SessionTreeEntry[]; metadata?: TMetadata }) {\n\t\tthis.entries = options?.entries ? [...options.entries] : [];\n\t\tthis.byId = new Map(this.entries.map((entry) => [entry.id, entry]));\n\t\tthis.labelsById = buildLabelsById(this.entries);\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.entries) this.leafId = leafIdAfterEntry(entry);\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\tthis.metadata = options?.metadata ?? ({ id: uuidv7(), createdAt: new Date().toISOString() } as TMetadata);\n\t}\n\n\tasync getMetadata(): Promise<TMetadata> {\n\t\treturn this.metadata;\n\t}\n\n\tasync getLeafId(): Promise<string | null> {\n\t\tif (this.leafId !== null && !this.byId.has(this.leafId)) {\n\t\t\tthrow new SessionError(\"invalid_session\", `Entry ${this.leafId} not found`);\n\t\t}\n\t\treturn this.leafId;\n\t}\n\n\tasync setLeafId(leafId: string | null): Promise<void> {\n\t\tif (leafId !== null && !this.byId.has(leafId)) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\t}\n\t\tconst entry: LeafEntry = {\n\t\t\ttype: \"leaf\",\n\t\t\tid: generateEntryId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId: leafId,\n\t\t};\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = leafId;\n\t}\n\n\tasync createEntryId(): Promise<string> {\n\t\treturn generateEntryId(this.byId);\n\t}\n\n\tasync appendEntry(entry: SessionTreeEntry): Promise<void> {\n\t\tthis.entries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tupdateLabelCache(this.labelsById, entry);\n\t\tthis.leafId = leafIdAfterEntry(entry);\n\t}\n\n\tasync getEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.byId.get(id);\n\t}\n\n\tasync findEntries<TType extends SessionTreeEntry[\"type\"]>(\n\t\ttype: TType,\n\t): Promise<Array<Extract<SessionTreeEntry, { type: TType }>>> {\n\t\treturn this.entries.filter((entry): entry is Extract<SessionTreeEntry, { type: TType }> => entry.type === type);\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\tasync getPathToRoot(leafId: string | null): Promise<SessionTreeEntry[]> {\n\t\tif (leafId === null) return [];\n\t\tconst path: SessionTreeEntry[] = [];\n\t\tlet current = this.byId.get(leafId);\n\t\tif (!current) throw new SessionError(\"not_found\", `Entry ${leafId} not found`);\n\t\twhile (current) {\n\t\t\tpath.unshift(current);\n\t\t\tif (!current.parentId) break;\n\t\t\tconst parent = this.byId.get(current.parentId);\n\t\t\tif (!parent) throw new SessionError(\"invalid_session\", `Entry ${current.parentId} not found`);\n\t\t\tcurrent = parent;\n\t\t}\n\t\treturn path;\n\t}\n\n\tasync getEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn [...this.entries];\n\t}\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { type FileError, type Result, type SessionMetadata, type SessionStorage, type SessionTreeEntry } from "../types.js";
2
- import { Session } from "./session.js";
1
+ import { type FileError, type Result, type SessionMetadata, type SessionStorage, type SessionTreeEntry } from "../types.ts";
2
+ import { Session } from "./session.ts";
3
3
  export declare function createSessionId(): string;
4
4
  export declare function createTimestamp(): string;
5
5
  export declare function toSession<TMetadata extends SessionMetadata>(storage: SessionStorage<TMetadata>): Session<TMetadata>;
@@ -1 +1 @@
1
- {"version":3,"file":"repo-utils.d.ts","sourceRoot":"","sources":["../../../src/harness/session/repo-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,SAAS,EACd,KAAK,MAAM,EAEX,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,wBAAgB,eAAe,IAAI,MAAM,CAExC;AAED,wBAAgB,eAAe,IAAI,MAAM,CAExC;AAED,wBAAgB,SAAS,CAAC,SAAS,SAAS,eAAe,EAAE,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,CAEnH;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAM7G;AAED,wBAAsB,gBAAgB,CACrC,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAA;CAAE,GACvD,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAgB7B","sourcesContent":["import {\n\ttype FileError,\n\ttype Result,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.js\";\nimport { Session } from \"./session.js\";\nimport { uuidv7 } from \"./uuid.js\";\n\nexport function createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function createTimestamp(): string {\n\treturn new Date().toISOString();\n}\n\nexport function toSession<TMetadata extends SessionMetadata>(storage: SessionStorage<TMetadata>): Session<TMetadata> {\n\treturn new Session(storage);\n}\n\nexport function getFileSystemResultOrThrow<TValue>(result: Result<TValue, FileError>, message: string): TValue {\n\tif (!result.ok) {\n\t\tconst code = result.error.code === \"not_found\" ? \"not_found\" : \"storage\";\n\t\tthrow new SessionError(code, `${message}: ${result.error.message}`, result.error);\n\t}\n\treturn result.value;\n}\n\nexport async function getEntriesToFork(\n\tstorage: SessionStorage,\n\toptions: { entryId?: string; position?: \"before\" | \"at\" },\n): Promise<SessionTreeEntry[]> {\n\tif (!options.entryId) return storage.getEntries();\n\tconst target = await storage.getEntry(options.entryId);\n\tif (!target) {\n\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} not found`);\n\t}\n\tlet effectiveLeafId: string | null;\n\tif ((options.position ?? \"before\") === \"at\") {\n\t\teffectiveLeafId = target.id;\n\t} else {\n\t\tif (target.type !== \"message\" || target.message.role !== \"user\") {\n\t\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} is not a user message`);\n\t\t}\n\t\teffectiveLeafId = target.parentId;\n\t}\n\treturn storage.getPathToRoot(effectiveLeafId);\n}\n"]}
1
+ {"version":3,"file":"repo-utils.d.ts","sourceRoot":"","sources":["../../../src/harness/session/repo-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,SAAS,EACd,KAAK,MAAM,EAEX,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAGvC,wBAAgB,eAAe,IAAI,MAAM,CAExC;AAED,wBAAgB,eAAe,IAAI,MAAM,CAExC;AAED,wBAAgB,SAAS,CAAC,SAAS,SAAS,eAAe,EAAE,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,CAEnH;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAM7G;AAED,wBAAsB,gBAAgB,CACrC,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAA;CAAE,GACvD,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAgB7B","sourcesContent":["import {\n\ttype FileError,\n\ttype Result,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.ts\";\nimport { Session } from \"./session.ts\";\nimport { uuidv7 } from \"./uuid.ts\";\n\nexport function createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function createTimestamp(): string {\n\treturn new Date().toISOString();\n}\n\nexport function toSession<TMetadata extends SessionMetadata>(storage: SessionStorage<TMetadata>): Session<TMetadata> {\n\treturn new Session(storage);\n}\n\nexport function getFileSystemResultOrThrow<TValue>(result: Result<TValue, FileError>, message: string): TValue {\n\tif (!result.ok) {\n\t\tconst code = result.error.code === \"not_found\" ? \"not_found\" : \"storage\";\n\t\tthrow new SessionError(code, `${message}: ${result.error.message}`, result.error);\n\t}\n\treturn result.value;\n}\n\nexport async function getEntriesToFork(\n\tstorage: SessionStorage,\n\toptions: { entryId?: string; position?: \"before\" | \"at\" },\n): Promise<SessionTreeEntry[]> {\n\tif (!options.entryId) return storage.getEntries();\n\tconst target = await storage.getEntry(options.entryId);\n\tif (!target) {\n\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} not found`);\n\t}\n\tlet effectiveLeafId: string | null;\n\tif ((options.position ?? \"before\") === \"at\") {\n\t\teffectiveLeafId = target.id;\n\t} else {\n\t\tif (target.type !== \"message\" || target.message.role !== \"user\") {\n\t\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} is not a user message`);\n\t\t}\n\t\teffectiveLeafId = target.parentId;\n\t}\n\treturn storage.getPathToRoot(effectiveLeafId);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"repo-utils.js","sourceRoot":"","sources":["../../../src/harness/session/repo-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,YAAY,GAIZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,MAAM,UAAU,eAAe,GAAW;IACzC,OAAO,MAAM,EAAE,CAAC;AAAA,CAChB;AAED,MAAM,UAAU,eAAe,GAAW;IACzC,OAAO,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAAA,CAChC;AAED,MAAM,UAAU,SAAS,CAAoC,OAAkC,EAAsB;IACpH,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;AAAA,CAC5B;AAED,MAAM,UAAU,0BAA0B,CAAS,MAAiC,EAAE,OAAe,EAAU;IAC9G,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QAChB,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC;QACzE,MAAM,IAAI,YAAY,CAAC,IAAI,EAAE,GAAG,OAAO,KAAK,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IACnF,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC;AAAA,CACpB;AAED,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACrC,OAAuB,EACvB,OAAyD,EAC3B;IAC9B,IAAI,CAAC,OAAO,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC,UAAU,EAAE,CAAC;IAClD,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACvD,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,SAAS,OAAO,CAAC,OAAO,YAAY,CAAC,CAAC;IACrF,CAAC;IACD,IAAI,eAA8B,CAAC;IACnC,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,KAAK,IAAI,EAAE,CAAC;QAC7C,eAAe,GAAG,MAAM,CAAC,EAAE,CAAC;IAC7B,CAAC;SAAM,CAAC;QACP,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACjE,MAAM,IAAI,YAAY,CAAC,qBAAqB,EAAE,SAAS,OAAO,CAAC,OAAO,wBAAwB,CAAC,CAAC;QACjG,CAAC;QACD,eAAe,GAAG,MAAM,CAAC,QAAQ,CAAC;IACnC,CAAC;IACD,OAAO,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;AAAA,CAC9C","sourcesContent":["import {\n\ttype FileError,\n\ttype Result,\n\tSessionError,\n\ttype SessionMetadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.js\";\nimport { Session } from \"./session.js\";\nimport { uuidv7 } from \"./uuid.js\";\n\nexport function createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function createTimestamp(): string {\n\treturn new Date().toISOString();\n}\n\nexport function toSession<TMetadata extends SessionMetadata>(storage: SessionStorage<TMetadata>): Session<TMetadata> {\n\treturn new Session(storage);\n}\n\nexport function getFileSystemResultOrThrow<TValue>(result: Result<TValue, FileError>, message: string): TValue {\n\tif (!result.ok) {\n\t\tconst code = result.error.code === \"not_found\" ? \"not_found\" : \"storage\";\n\t\tthrow new SessionError(code, `${message}: ${result.error.message}`, result.error);\n\t}\n\treturn result.value;\n}\n\nexport async function getEntriesToFork(\n\tstorage: SessionStorage,\n\toptions: { entryId?: string; position?: \"before\" | \"at\" },\n): Promise<SessionTreeEntry[]> {\n\tif (!options.entryId) return storage.getEntries();\n\tconst target = await storage.getEntry(options.entryId);\n\tif (!target) {\n\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} not found`);\n\t}\n\tlet effectiveLeafId: string | null;\n\tif ((options.position ?? \"before\") === \"at\") {\n\t\teffectiveLeafId = target.id;\n\t} else {\n\t\tif (target.type !== \"message\" || target.message.role !== \"user\") {\n\t\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} is not a user message`);\n\t\t}\n\t\teffectiveLeafId = target.parentId;\n\t}\n\treturn storage.getPathToRoot(effectiveLeafId);\n}\n"]}
1
+ {"version":3,"file":"repo-utils.js","sourceRoot":"","sources":["../../../src/harness/session/repo-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,YAAY,GAIZ,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,MAAM,UAAU,eAAe,GAAW;IACzC,OAAO,MAAM,EAAE,CAAC;AAAA,CAChB;AAED,MAAM,UAAU,eAAe,GAAW;IACzC,OAAO,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAAA,CAChC;AAED,MAAM,UAAU,SAAS,CAAoC,OAAkC,EAAsB;IACpH,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;AAAA,CAC5B;AAED,MAAM,UAAU,0BAA0B,CAAS,MAAiC,EAAE,OAAe,EAAU;IAC9G,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;Q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Metadata,\n\ttype SessionStorage,\n\ttype SessionTreeEntry,\n} from \"../types.ts\";\nimport { Session } from \"./session.ts\";\nimport { uuidv7 } from \"./uuid.ts\";\n\nexport function createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function createTimestamp(): string {\n\treturn new Date().toISOString();\n}\n\nexport function toSession<TMetadata extends SessionMetadata>(storage: SessionStorage<TMetadata>): Session<TMetadata> {\n\treturn new Session(storage);\n}\n\nexport function getFileSystemResultOrThrow<TValue>(result: Result<TValue, FileError>, message: string): TValue {\n\tif (!result.ok) {\n\t\tconst code = result.error.code === \"not_found\" ? \"not_found\" : \"storage\";\n\t\tthrow new SessionError(code, `${message}: ${result.error.message}`, result.error);\n\t}\n\treturn result.value;\n}\n\nexport async function getEntriesToFork(\n\tstorage: SessionStorage,\n\toptions: { entryId?: string; position?: \"before\" | \"at\" },\n): Promise<SessionTreeEntry[]> {\n\tif (!options.entryId) return storage.getEntries();\n\tconst target = await storage.getEntry(options.entryId);\n\tif (!target) {\n\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} not found`);\n\t}\n\tlet effectiveLeafId: string | null;\n\tif ((options.position ?? \"before\") === \"at\") {\n\t\teffectiveLeafId = target.id;\n\t} else {\n\t\tif (target.type !== \"message\" || target.message.role !== \"user\") {\n\t\t\tthrow new SessionError(\"invalid_fork_target\", `Entry ${options.entryId} is not a user message`);\n\t\t}\n\t\teffectiveLeafId = target.parentId;\n\t}\n\treturn storage.getPathToRoot(effectiveLeafId);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
2
- import type { AgentMessage } from "../../types.js";
3
- import type { SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry } from "../types.js";
2
+ import type { AgentMessage } from "../../types.ts";
3
+ import type { SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry } from "../types.ts";
4
4
  export declare function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext;
5
5
  export declare class Session<TMetadata extends SessionMetadata = SessionMetadata> {
6
6
  private storage;
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/harness/session/session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,KAAK,EAQX,cAAc,EAEd,eAAe,EACf,cAAc,EACd,gBAAgB,EAEhB,MAAM,aAAa,CAAC;AAGrB,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,gBAAgB,EAAE,GAAG,cAAc,CAuDnF;AAED,qBAAa,OAAO,CAAC,SAAS,SAAS,eAAe,GAAG,eAAe;IACvE,OAAO,CAAC,OAAO,CAA4B;IAE3C,YAAY,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,EAE7C;IAED,WAAW,IAAI,OAAO,CAAC,SAAS,CAAC,CAEhC;IAED,UAAU,IAAI,cAAc,CAAC,SAAS,CAAC,CAEtC;IAED,SAAS,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAElC;IAED,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAE1D;IAED,UAAU,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAExC;IAEK,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAG5D;IAEK,YAAY,IAAI,OAAO,CAAC,cAAc,CAAC,CAE5C;IAED,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAEhD;IAEK,cAAc,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAGlD;YAEa,gBAAgB;IAKxB,aAAa,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAQ1D;IAEK,yBAAyB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAQtE;IAEK,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAS1E;IAEK,gBAAgB,CAAC,CAAC,GAAG,OAAO,EACjC,OAAO,EAAE,MAAM,EACf,gBAAgB,EAAE,MAAM,EACxB,YAAY,EAAE,MAAM,EACpB,OAAO,CAAC,EAAE,CAAC,EACX,QAAQ,CAAC,EAAE,OAAO,GAChB,OAAO,CAAC,MAAM,CAAC,CAYjB;IAEK,iBAAiB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAS3E;IAEK,wBAAwB,CAAC,CAAC,GAAG,OAAO,EACzC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,CAAC,GACT,OAAO,CAAC,MAAM,CAAC,CAWjB;IAEK,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,CAY9E;IAEK,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAQrD;IAEK,MAAM,CACX,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,OAAO,CAAC,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,GAClE,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgB7B;CACD","sourcesContent":["import type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { AgentMessage } from \"../../types.js\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tCustomMessageEntry,\n\tLabelEntry,\n\tMessageEntry,\n\tModelChangeEntry,\n\tSessionContext,\n\tSessionInfoEntry,\n\tSessionMetadata,\n\tSessionStorage,\n\tSessionTreeEntry,\n\tThinkingLevelChangeEntry,\n} from \"../types.js\";\nimport { SessionError } from \"../types.js\";\n\nexport function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t} else if (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tconst messages: AgentMessage[] = [];\n\tconst appendMessage = (entry: SessionTreeEntry) => {\n\t\tif (entry.type === \"message\") {\n\t\t\tmessages.push(entry.message as AgentMessage);\n\t\t} else if (entry.type === \"custom_message\") {\n\t\t\tmessages.push(\n\t\t\t\tcreateCustomMessage(\n\t\t\t\t\tentry.customType,\n\t\t\t\t\tentry.content as string | (TextContent | ImageContent)[],\n\t\t\t\t\tentry.display,\n\t\t\t\t\tentry.details,\n\t\t\t\t\tentry.timestamp,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (entry.type === \"branch_summary\" && entry.summary) {\n\t\t\tmessages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));\n\t\t}\n\t};\n\n\tif (compaction) {\n\t\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\t\tconst compactionIdx = pathEntries.findIndex((e) => e.type === \"compaction\" && e.id === compaction.id);\n\t\tlet foundFirstKept = false;\n\t\tfor (let i = 0; i < compactionIdx; i++) {\n\t\t\tconst entry = pathEntries[i]!;\n\t\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\t\tif (foundFirstKept) appendMessage(entry);\n\t\t}\n\t\tfor (let i = compactionIdx + 1; i < pathEntries.length; i++) {\n\t\t\tappendMessage(pathEntries[i]!);\n\t\t}\n\t} else {\n\t\tfor (const entry of pathEntries) {\n\t\t\tappendMessage(entry);\n\t\t}\n\t}\n\n\treturn { messages, thinkingLevel, model };\n}\n\nexport class Session<TMetadata extends SessionMetadata = SessionMetadata> {\n\tprivate storage: SessionStorage<TMetadata>;\n\n\tconstructor(storage: SessionStorage<TMetadata>) {\n\t\tthis.storage = storage;\n\t}\n\n\tgetMetadata(): Promise<TMetadata> {\n\t\treturn this.storage.getMetadata();\n\t}\n\n\tgetStorage(): SessionStorage<TMetadata> {\n\t\treturn this.storage;\n\t}\n\n\tgetLeafId(): Promise<string | null> {\n\t\treturn this.storage.getLeafId();\n\t}\n\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.storage.getEntry(id);\n\t}\n\n\tgetEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn this.storage.getEntries();\n\t}\n\n\tasync getBranch(fromId?: string): Promise<SessionTreeEntry[]> {\n\t\tconst leafId = fromId ?? (await this.storage.getLeafId());\n\t\treturn this.storage.getPathToRoot(leafId);\n\t}\n\n\tasync buildContext(): Promise<SessionContext> {\n\t\treturn buildSessionContext(await this.getBranch());\n\t}\n\n\tgetLabel(id: string): Promise<string | undefined> {\n\t\treturn this.storage.getLabel(id);\n\t}\n\n\tasync getSessionName(): Promise<string | undefined> {\n\t\tconst entries = await this.storage.findEntries(\"session_info\");\n\t\treturn entries[entries.length - 1]?.name?.trim() || undefined;\n\t}\n\n\tprivate async appendTypedEntry<TEntry extends SessionTreeEntry>(entry: TEntry): Promise<string> {\n\t\tawait this.storage.appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t} satisfies MessageEntry);\n\t}\n\n\tasync appendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t} satisfies ThinkingLevelChangeEntry);\n\t}\n\n\tasync appendModelChange(provider: string, modelId: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"model_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t} satisfies ModelChangeEntry);\n\t}\n\n\tasync appendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"compaction\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tfromHook,\n\t\t} satisfies CompactionEntry<T>);\n\t}\n\n\tasync appendCustomEntry(customType: string, data?: unknown): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t} satisfies CustomEntry);\n\t}\n\n\tasync appendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom_message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t} satisfies CustomMessageEntry<T>);\n\t}\n\n\tasync appendLabel(targetId: string, label: string | undefined): Promise<string> {\n\t\tif (!(await this.storage.getEntry(targetId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${targetId} not found`);\n\t\t}\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"label\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t} satisfies LabelEntry);\n\t}\n\n\tasync appendSessionName(name: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"session_info\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: name.trim(),\n\t\t} satisfies SessionInfoEntry);\n\t}\n\n\tasync moveTo(\n\t\tentryId: string | null,\n\t\tsummary?: { summary: string; details?: unknown; fromHook?: boolean },\n\t): Promise<string | undefined> {\n\t\tif (entryId !== null && !(await this.storage.getEntry(entryId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${entryId} not found`);\n\t\t}\n\t\tawait this.storage.setLeafId(entryId);\n\t\tif (!summary) return undefined;\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: entryId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: entryId ?? \"root\",\n\t\t\tsummary: summary.summary,\n\t\t\tdetails: summary.details,\n\t\t\tfromHook: summary.fromHook,\n\t\t} satisfies BranchSummaryEntry);\n\t}\n}\n"]}
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/harness/session/session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,KAAK,EAQX,cAAc,EAEd,eAAe,EACf,cAAc,EACd,gBAAgB,EAEhB,MAAM,aAAa,CAAC;AAGrB,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,gBAAgB,EAAE,GAAG,cAAc,CAuDnF;AAED,qBAAa,OAAO,CAAC,SAAS,SAAS,eAAe,GAAG,eAAe;IACvE,OAAO,CAAC,OAAO,CAA4B;IAE3C,YAAY,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,EAE7C;IAED,WAAW,IAAI,OAAO,CAAC,SAAS,CAAC,CAEhC;IAED,UAAU,IAAI,cAAc,CAAC,SAAS,CAAC,CAEtC;IAED,SAAS,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAElC;IAED,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAE1D;IAED,UAAU,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAExC;IAEK,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAG5D;IAEK,YAAY,IAAI,OAAO,CAAC,cAAc,CAAC,CAE5C;IAED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QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;KAAE,GAClE,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgB7B;CACD","sourcesContent":["import type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { AgentMessage } from \"../../types.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tCustomMessageEntry,\n\tLabelEntry,\n\tMessageEntry,\n\tModelChangeEntry,\n\tSessionContext,\n\tSessionInfoEntry,\n\tSessionMetadata,\n\tSessionStorage,\n\tSessionTreeEntry,\n\tThinkingLevelChangeEntry,\n} from \"../types.ts\";\nimport { SessionError } from \"../types.ts\";\n\nexport function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t} else if (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tconst messages: AgentMessage[] = [];\n\tconst appendMessage = (entry: SessionTreeEntry) => {\n\t\tif (entry.type === \"message\") {\n\t\t\tmessages.push(entry.message as AgentMessage);\n\t\t} else if (entry.type === \"custom_message\") {\n\t\t\tmessages.push(\n\t\t\t\tcreateCustomMessage(\n\t\t\t\t\tentry.customType,\n\t\t\t\t\tentry.content as string | (TextContent | ImageContent)[],\n\t\t\t\t\tentry.display,\n\t\t\t\t\tentry.details,\n\t\t\t\t\tentry.timestamp,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (entry.type === \"branch_summary\" && entry.summary) {\n\t\t\tmessages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));\n\t\t}\n\t};\n\n\tif (compaction) {\n\t\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\t\tconst compactionIdx = pathEntries.findIndex((e) => e.type === \"compaction\" && e.id === compaction.id);\n\t\tlet foundFirstKept = false;\n\t\tfor (let i = 0; i < compactionIdx; i++) {\n\t\t\tconst entry = pathEntries[i]!;\n\t\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\t\tif (foundFirstKept) appendMessage(entry);\n\t\t}\n\t\tfor (let i = compactionIdx + 1; i < pathEntries.length; i++) {\n\t\t\tappendMessage(pathEntries[i]!);\n\t\t}\n\t} else {\n\t\tfor (const entry of pathEntries) {\n\t\t\tappendMessage(entry);\n\t\t}\n\t}\n\n\treturn { messages, thinkingLevel, model };\n}\n\nexport class Session<TMetadata extends SessionMetadata = SessionMetadata> {\n\tprivate storage: SessionStorage<TMetadata>;\n\n\tconstructor(storage: SessionStorage<TMetadata>) {\n\t\tthis.storage = storage;\n\t}\n\n\tgetMetadata(): Promise<TMetadata> {\n\t\treturn this.storage.getMetadata();\n\t}\n\n\tgetStorage(): SessionStorage<TMetadata> {\n\t\treturn this.storage;\n\t}\n\n\tgetLeafId(): Promise<string | null> {\n\t\treturn this.storage.getLeafId();\n\t}\n\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.storage.getEntry(id);\n\t}\n\n\tgetEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn this.storage.getEntries();\n\t}\n\n\tasync getBranch(fromId?: string): Promise<SessionTreeEntry[]> {\n\t\tconst leafId = fromId ?? (await this.storage.getLeafId());\n\t\treturn this.storage.getPathToRoot(leafId);\n\t}\n\n\tasync buildContext(): Promise<SessionContext> {\n\t\treturn buildSessionContext(await this.getBranch());\n\t}\n\n\tgetLabel(id: string): Promise<string | undefined> {\n\t\treturn this.storage.getLabel(id);\n\t}\n\n\tasync getSessionName(): Promise<string | undefined> {\n\t\tconst entries = await this.storage.findEntries(\"session_info\");\n\t\treturn entries[entries.length - 1]?.name?.trim() || undefined;\n\t}\n\n\tprivate async appendTypedEntry<TEntry extends SessionTreeEntry>(entry: TEntry): Promise<string> {\n\t\tawait this.storage.appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t} satisfies MessageEntry);\n\t}\n\n\tasync appendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t} satisfies ThinkingLevelChangeEntry);\n\t}\n\n\tasync appendModelChange(provider: string, modelId: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"model_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t} satisfies ModelChangeEntry);\n\t}\n\n\tasync appendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"compaction\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tfromHook,\n\t\t} satisfies CompactionEntry<T>);\n\t}\n\n\tasync appendCustomEntry(customType: string, data?: unknown): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t} satisfies CustomEntry);\n\t}\n\n\tasync appendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom_message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t} satisfies CustomMessageEntry<T>);\n\t}\n\n\tasync appendLabel(targetId: string, label: string | undefined): Promise<string> {\n\t\tif (!(await this.storage.getEntry(targetId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${targetId} not found`);\n\t\t}\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"label\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t} satisfies LabelEntry);\n\t}\n\n\tasync appendSessionName(name: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"session_info\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: name.trim(),\n\t\t} satisfies SessionInfoEntry);\n\t}\n\n\tasync moveTo(\n\t\tentryId: string | null,\n\t\tsummary?: { summary: string; details?: unknown; fromHook?: boolean },\n\t): Promise<string | undefined> {\n\t\tif (entryId !== null && !(await this.storage.getEntry(entryId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${entryId} not found`);\n\t\t}\n\t\tawait this.storage.setLeafId(entryId);\n\t\tif (!summary) return undefined;\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: entryId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: entryId ?? \"root\",\n\t\t\tsummary: summary.summary,\n\t\t\tdetails: summary.details,\n\t\t\tfromHook: summary.fromHook,\n\t\t} satisfies BranchSummaryEntry);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/harness/session/session.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAgBjH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,UAAU,mBAAmB,CAAC,WAA+B,EAAkB;IACpF,IAAI,aAAa,GAAG,KAAK,CAAC;IAC1B,IAAI,KAAK,GAAiD,IAAI,CAAC;IAC/D,IAAI,UAAU,GAA2B,IAAI,CAAC;IAE9C,KAAK,MAAM,KAAK,IAAI,WAAW,EAAE,CAAC;QACjC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;QACrC,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;YAC1C,KAAK,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC9D,CAAC;aAAM,I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entMessage } from \"../../types.js\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.js\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tCustomMessageEntry,\n\tLabelEntry,\n\tMessageEntry,\n\tModelChangeEntry,\n\tSessionContext,\n\tSessionInfoEntry,\n\tSessionMetadata,\n\tSessionStorage,\n\tSessionTreeEntry,\n\tThinkingLevelChangeEntry,\n} from \"../types.js\";\nimport { SessionError } from \"../types.js\";\n\nexport function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t} else if (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tconst messages: AgentMessage[] = [];\n\tconst appendMessage = (entry: SessionTreeEntry) => {\n\t\tif (entry.type === \"message\") {\n\t\t\tmessages.push(entry.message as AgentMessage);\n\t\t} else if (entry.type === \"custom_message\") {\n\t\t\tmessages.push(\n\t\t\t\tcreateCustomMessage(\n\t\t\t\t\tentry.customType,\n\t\t\t\t\tentry.content as string | (TextContent | ImageContent)[],\n\t\t\t\t\tentry.display,\n\t\t\t\t\tentry.details,\n\t\t\t\t\tentry.timestamp,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (entry.type === \"branch_summary\" && entry.summary) {\n\t\t\tmessages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));\n\t\t}\n\t};\n\n\tif (compaction) {\n\t\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\t\tconst compactionIdx = pathEntries.findIndex((e) => e.type === \"compaction\" && e.id === compaction.id);\n\t\tlet foundFirstKept = false;\n\t\tfor (let i = 0; i < compactionIdx; i++) {\n\t\t\tconst entry = pathEntries[i]!;\n\t\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\t\tif (foundFirstKept) appendMessage(entry);\n\t\t}\n\t\tfor (let i = compactionIdx + 1; i < pathEntries.length; i++) {\n\t\t\tappendMessage(pathEntries[i]!);\n\t\t}\n\t} else {\n\t\tfor (const entry of pathEntries) {\n\t\t\tappendMessage(entry);\n\t\t}\n\t}\n\n\treturn { messages, thinkingLevel, model };\n}\n\nexport class Session<TMetadata extends SessionMetadata = SessionMetadata> {\n\tprivate storage: SessionStorage<TMetadata>;\n\n\tconstructor(storage: SessionStorage<TMetadata>) {\n\t\tthis.storage = storage;\n\t}\n\n\tgetMetadata(): Promise<TMetadata> {\n\t\treturn this.storage.getMetadata();\n\t}\n\n\tgetStorage(): SessionStorage<TMetadata> {\n\t\treturn this.storage;\n\t}\n\n\tgetLeafId(): Promise<string | null> {\n\t\treturn this.storage.getLeafId();\n\t}\n\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.storage.getEntry(id);\n\t}\n\n\tgetEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn this.storage.getEntries();\n\t}\n\n\tasync getBranch(fromId?: string): Promise<SessionTreeEntry[]> {\n\t\tconst leafId = fromId ?? (await this.storage.getLeafId());\n\t\treturn this.storage.getPathToRoot(leafId);\n\t}\n\n\tasync buildContext(): Promise<SessionContext> {\n\t\treturn buildSessionContext(await this.getBranch());\n\t}\n\n\tgetLabel(id: string): Promise<string | undefined> {\n\t\treturn this.storage.getLabel(id);\n\t}\n\n\tasync getSessionName(): Promise<string | undefined> {\n\t\tconst entries = await this.storage.findEntries(\"session_info\");\n\t\treturn entries[entries.length - 1]?.name?.trim() || undefined;\n\t}\n\n\tprivate async appendTypedEntry<TEntry extends SessionTreeEntry>(entry: TEntry): Promise<string> {\n\t\tawait this.storage.appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t} satisfies MessageEntry);\n\t}\n\n\tasync appendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t} satisfies ThinkingLevelChangeEntry);\n\t}\n\n\tasync appendModelChange(provider: string, modelId: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"model_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t} satisfies ModelChangeEntry);\n\t}\n\n\tasync appendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"compaction\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tfromHook,\n\t\t} satisfies CompactionEntry<T>);\n\t}\n\n\tasync appendCustomEntry(customType: string, data?: unknown): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t} satisfies CustomEntry);\n\t}\n\n\tasync appendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom_message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t} satisfies CustomMessageEntry<T>);\n\t}\n\n\tasync appendLabel(targetId: string, label: string | undefined): Promise<string> {\n\t\tif (!(await this.storage.getEntry(targetId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${targetId} not found`);\n\t\t}\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"label\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t} satisfies LabelEntry);\n\t}\n\n\tasync appendSessionName(name: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"session_info\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: name.trim(),\n\t\t} satisfies SessionInfoEntry);\n\t}\n\n\tasync moveTo(\n\t\tentryId: string | null,\n\t\tsummary?: { summary: string; details?: unknown; fromHook?: boolean },\n\t): Promise<string | undefined> {\n\t\tif (entryId !== null && !(await this.storage.getEntry(entryId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${entryId} not found`);\n\t\t}\n\t\tawait this.storage.setLeafId(entryId);\n\t\tif (!summary) return undefined;\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: entryId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: entryId ?? \"root\",\n\t\t\tsummary: summary.summary,\n\t\t\tdetails: summary.details,\n\t\t\tfromHook: summary.fromHook,\n\t\t} satisfies BranchSummaryEntry);\n\t}\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/harness/session/session.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,8BAA8B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAgBjH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,MAAM,UAAU,mBAAmB,CAAC,WAA+B,EAAkB;IACpF,IAAI,aAAa,GAAG,KAAK,CAAC;IAC1B,IAAI,KAAK,GAAiD,IAAI,CAAC;IAC/D,IAAI,UAAU,GAA2B,IAAI,CAAC;IAE9C,KAAK,MAAM,KAAK,IAAI,WAAW,EAAE,CAAC;QACjC,IAAI,KAAK,CAAC,IAAI,KAAK,uBAAuB,EAAE,CAAC;YAC5C,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;QACrC,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;YAC1C,KAAK,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;QAC9D,CAAC;aAAM,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YAC3E,KAAK,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KA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AAC,aAAa,EAAE;YACtC,QAAQ,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE;YACxC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE;SACU,CAAC,CAAC;IAAA,CAC9B;IAED,KAAK,CAAC,MAAM,CACX,OAAsB,EACtB,OAAoE,EACtC;QAC9B,IAAI,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;YACjE,MAAM,IAAI,YAAY,CAAC,WAAW,EAAE,SAAS,OAAO,YAAY,CAAC,CAAC;QACnE,CAAC;QACD,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,OAAO;YAAE,OAAO,SAAS,CAAC;QAC/B,OAAO,IAAI,CAAC,gBAAgB,CAAC;YAC5B,IAAI,EAAE,gBAAgB;YACtB,EAAE,EAAE,MAAM,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE;YACtC,QAAQ,EAAE,OAAO;YACjB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,MAAM,EAAE,OAAO,IAAI,MAAM;YACzB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;SACG,CAAC,CAAC;IAAA,CAChC;CACD","sourcesContent":["import type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { AgentMessage } from \"../../types.ts\";\nimport { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tCustomMessageEntry,\n\tLabelEntry,\n\tMessageEntry,\n\tModelChangeEntry,\n\tSessionContext,\n\tSessionInfoEntry,\n\tSessionMetadata,\n\tSessionStorage,\n\tSessionTreeEntry,\n\tThinkingLevelChangeEntry,\n} from \"../types.ts\";\nimport { SessionError } from \"../types.ts\";\n\nexport function buildSessionContext(pathEntries: SessionTreeEntry[]): SessionContext {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of pathEntries) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t} else if (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tconst messages: AgentMessage[] = [];\n\tconst appendMessage = (entry: SessionTreeEntry) => {\n\t\tif (entry.type === \"message\") {\n\t\t\tmessages.push(entry.message as AgentMessage);\n\t\t} else if (entry.type === \"custom_message\") {\n\t\t\tmessages.push(\n\t\t\t\tcreateCustomMessage(\n\t\t\t\t\tentry.customType,\n\t\t\t\t\tentry.content as string | (TextContent | ImageContent)[],\n\t\t\t\t\tentry.display,\n\t\t\t\t\tentry.details,\n\t\t\t\t\tentry.timestamp,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (entry.type === \"branch_summary\" && entry.summary) {\n\t\t\tmessages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));\n\t\t}\n\t};\n\n\tif (compaction) {\n\t\tmessages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));\n\t\tconst compactionIdx = pathEntries.findIndex((e) => e.type === \"compaction\" && e.id === compaction.id);\n\t\tlet foundFirstKept = false;\n\t\tfor (let i = 0; i < compactionIdx; i++) {\n\t\t\tconst entry = pathEntries[i]!;\n\t\t\tif (entry.id === compaction.firstKeptEntryId) foundFirstKept = true;\n\t\t\tif (foundFirstKept) appendMessage(entry);\n\t\t}\n\t\tfor (let i = compactionIdx + 1; i < pathEntries.length; i++) {\n\t\t\tappendMessage(pathEntries[i]!);\n\t\t}\n\t} else {\n\t\tfor (const entry of pathEntries) {\n\t\t\tappendMessage(entry);\n\t\t}\n\t}\n\n\treturn { messages, thinkingLevel, model };\n}\n\nexport class Session<TMetadata extends SessionMetadata = SessionMetadata> {\n\tprivate storage: SessionStorage<TMetadata>;\n\n\tconstructor(storage: SessionStorage<TMetadata>) {\n\t\tthis.storage = storage;\n\t}\n\n\tgetMetadata(): Promise<TMetadata> {\n\t\treturn this.storage.getMetadata();\n\t}\n\n\tgetStorage(): SessionStorage<TMetadata> {\n\t\treturn this.storage;\n\t}\n\n\tgetLeafId(): Promise<string | null> {\n\t\treturn this.storage.getLeafId();\n\t}\n\n\tgetEntry(id: string): Promise<SessionTreeEntry | undefined> {\n\t\treturn this.storage.getEntry(id);\n\t}\n\n\tgetEntries(): Promise<SessionTreeEntry[]> {\n\t\treturn this.storage.getEntries();\n\t}\n\n\tasync getBranch(fromId?: string): Promise<SessionTreeEntry[]> {\n\t\tconst leafId = fromId ?? (await this.storage.getLeafId());\n\t\treturn this.storage.getPathToRoot(leafId);\n\t}\n\n\tasync buildContext(): Promise<SessionContext> {\n\t\treturn buildSessionContext(await this.getBranch());\n\t}\n\n\tgetLabel(id: string): Promise<string | undefined> {\n\t\treturn this.storage.getLabel(id);\n\t}\n\n\tasync getSessionName(): Promise<string | undefined> {\n\t\tconst entries = await this.storage.findEntries(\"session_info\");\n\t\treturn entries[entries.length - 1]?.name?.trim() || undefined;\n\t}\n\n\tprivate async appendTypedEntry<TEntry extends SessionTreeEntry>(entry: TEntry): Promise<string> {\n\t\tawait this.storage.appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t} satisfies MessageEntry);\n\t}\n\n\tasync appendThinkingLevelChange(thinkingLevel: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t} satisfies ThinkingLevelChangeEntry);\n\t}\n\n\tasync appendModelChange(provider: string, modelId: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"model_change\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t} satisfies ModelChangeEntry);\n\t}\n\n\tasync appendCompaction<T = unknown>(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"compaction\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tfromHook,\n\t\t} satisfies CompactionEntry<T>);\n\t}\n\n\tasync appendCustomEntry(customType: string, data?: unknown): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t} satisfies CustomEntry);\n\t}\n\n\tasync appendCustomMessageEntry<T = unknown>(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"custom_message\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t} satisfies CustomMessageEntry<T>);\n\t}\n\n\tasync appendLabel(targetId: string, label: string | undefined): Promise<string> {\n\t\tif (!(await this.storage.getEntry(targetId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${targetId} not found`);\n\t\t}\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"label\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t} satisfies LabelEntry);\n\t}\n\n\tasync appendSessionName(name: string): Promise<string> {\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"session_info\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: await this.storage.getLeafId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: name.trim(),\n\t\t} satisfies SessionInfoEntry);\n\t}\n\n\tasync moveTo(\n\t\tentryId: string | null,\n\t\tsummary?: { summary: string; details?: unknown; fromHook?: boolean },\n\t): Promise<string | undefined> {\n\t\tif (entryId !== null && !(await this.storage.getEntry(entryId))) {\n\t\t\tthrow new SessionError(\"not_found\", `Entry ${entryId} not found`);\n\t\t}\n\t\tawait this.storage.setLeafId(entryId);\n\t\tif (!summary) return undefined;\n\t\treturn this.appendTypedEntry({\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: await this.storage.createEntryId(),\n\t\t\tparentId: entryId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: entryId ?? \"root\",\n\t\t\tsummary: summary.summary,\n\t\t\tdetails: summary.details,\n\t\t\tfromHook: summary.fromHook,\n\t\t} satisfies BranchSummaryEntry);\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type ExecutionEnv, type Skill } from "./types.js";
1
+ import { type ExecutionEnv, type Skill } from "./types.ts";
2
2
  export type SkillDiagnosticCode = "file_info_failed" | "list_failed" | "read_failed" | "parse_failed" | "invalid_metadata";
3
3
  /** Warning produced while loading skills. */
4
4
  export interface SkillDiagnostic {
@@ -1 +1 @@
1
- {"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../../src/harness/skills.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,YAAY,EAA8B,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAQhG,MAAM,MAAM,mBAAmB,GAC5B,kBAAkB,GAClB,aAAa,GACb,aAAa,GACb,cAAc,GACd,kBAAkB,CAAC;AAEtB,6CAA6C;AAC7C,MAAM,WAAW,eAAe;IAC/B,gEAAgE;IAChE,IAAI,EAAE,SAAS,CAAC;IAChB,8BAA8B;IAC9B,IAAI,EAAE,mBAAmB,CAAC;IAC1B,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;IAChB,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;CACb;AASD,2FAA2F;AAC3F,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,sBAAsB,CAAC,EAAE,MAAM,GAAG,MAAM,CAG3F;AAED;;;;;GAKG;AACH,wBAAsB,UAAU,CAC/B,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GACrB,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAAC,WAAW,EAAE,eAAe,EAAE,CAAA;CAAE,CAAC,CAuB9D;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,MAAM,SAAS,KAAK,GAAG,KAAK,EAC5E,GAAG,EAAE,YAAY,EACjB,MAAM,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC,EAChD,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,KAAK,MAAM,GAClD,OAAO,CAAC;IACV,MAAM,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IAClD,WAAW,EAAE,KAAK,CAAC,eAAe,GAAG;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC1D,CAAC,CAWD","sourcesContent":["import ignore from \"ignore\";\nimport { parse } from \"yaml\";\nimport { type ExecutionEnv, type FileInfo, type Result, type Skill, toError } from \"./types.js\";\n\nconst MAX_NAME_LENGTH = 64;\nconst MAX_DESCRIPTION_LENGTH = 1024;\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nexport type SkillDiagnosticCode =\n\t| \"file_info_failed\"\n\t| \"list_failed\"\n\t| \"read_failed\"\n\t| \"parse_failed\"\n\t| \"invalid_metadata\";\n\n/** Warning produced while loading skills. */\nexport interface SkillDiagnostic {\n\t/** Diagnostic severity. Currently only warnings are emitted. */\n\ttype: \"warning\";\n\t/** Stable diagnostic code. */\n\tcode: SkillDiagnosticCode;\n\t/** Human-readable diagnostic message. */\n\tmessage: string;\n\t/** Path associated with the diagnostic. */\n\tpath: string;\n}\n\ninterface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\n/** Format a skill invocation prompt, optionally appending additional user instructions. */\nexport function formatSkillInvocation(skill: Skill, additionalInstructions?: string): string {\n\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${dirnameEnvPath(skill.filePath)}.\\n\\n${skill.content}\\n</skill>`;\n\treturn additionalInstructions ? `${skillBlock}\\n\\n${additionalInstructions}` : skillBlock;\n}\n\n/**\n * Load skills from one or more directories.\n *\n * Traverses directories recursively, loads `SKILL.md` files, loads direct root `.md` files as skills, honors ignore files,\n * and returns diagnostics for invalid skill files. Missing input directories are skipped.\n */\nexport async function loadSkills(\n\tenv: ExecutionEnv,\n\tdirs: string | string[],\n): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[] }> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: SkillDiagnostic[] = [];\n\tfor (const dir of Array.isArray(dirs) ? dirs : [dirs]) {\n\t\tconst rootInfoResult = await env.fileInfo(dir);\n\t\tif (!rootInfoResult.ok) {\n\t\t\tif (rootInfoResult.error.code !== \"not_found\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\t\tmessage: rootInfoResult.error.message,\n\t\t\t\t\tpath: dir,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst rootInfo = rootInfoResult.value;\n\t\tif ((await resolveKind(env, rootInfo, diagnostics)) !== \"directory\") continue;\n\t\tconst result = await loadSkillsFromDirInternal(env, rootInfo.path, true, ignore(), rootInfo.path);\n\t\tskills.push(...result.skills);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\treturn { skills, diagnostics };\n}\n\n/**\n * Load skills from source-tagged directories.\n *\n * Source values are preserved exactly and attached to every loaded skill and diagnostic. The agent package does not\n * interpret source values; applications define their own provenance shape.\n */\nexport async function loadSourcedSkills<TSource, TSkill extends Skill = Skill>(\n\tenv: ExecutionEnv,\n\tinputs: Array<{ path: string; source: TSource }>,\n\tmapSkill?: (skill: Skill, source: TSource) => TSkill,\n): Promise<{\n\tskills: Array<{ skill: TSkill; source: TSource }>;\n\tdiagnostics: Array<SkillDiagnostic & { source: TSource }>;\n}> {\n\tconst skills: Array<{ skill: TSkill; source: TSource }> = [];\n\tconst diagnostics: Array<SkillDiagnostic & { source: TSource }> = [];\n\tfor (const input of inputs) {\n\t\tconst result = await loadSkills(env, input.path);\n\t\tfor (const skill of result.skills) {\n\t\t\tskills.push({ skill: mapSkill ? mapSkill(skill, input.source) : (skill as TSkill), source: input.source });\n\t\t}\n\t\tfor (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, source: input.source });\n\t}\n\treturn { skills, diagnostics };\n}\n\nasync function loadSkillsFromDirInternal(\n\tenv: ExecutionEnv,\n\tdir: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher: IgnoreMatcher,\n\trootDir: string,\n): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[] }> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: SkillDiagnostic[] = [];\n\n\tconst dirInfoResult = await env.fileInfo(dir);\n\tif (!dirInfoResult.ok) {\n\t\tif (dirInfoResult.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: dirInfoResult.error.message,\n\t\t\t\tpath: dir,\n\t\t\t});\n\t\t}\n\t\treturn { skills, diagnostics };\n\t}\n\tconst dirInfo = dirInfoResult.value;\n\tif ((await resolveKind(env, dirInfo, diagnostics)) !== \"directory\") return { skills, diagnostics };\n\n\tawait addIgnoreRules(env, ignoreMatcher, dir, rootDir, diagnostics);\n\n\tconst entriesResult = await env.listDir(dir);\n\tif (!entriesResult.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"list_failed\", message: entriesResult.error.message, path: dir });\n\t\treturn { skills, diagnostics };\n\t}\n\tconst entries = entriesResult.value;\n\n\tfor (const entry of entries) {\n\t\tif (entry.name !== \"SKILL.md\") continue;\n\t\tconst fullPath = entry.path;\n\t\tconst kind = await resolveKind(env, entry, diagnostics);\n\t\tif (kind !== \"file\") continue;\n\t\tconst relPath = relativeEnvPath(rootDir, fullPath);\n\t\tif (ignoreMatcher.ignores(relPath)) continue;\n\n\t\tconst result = await loadSkillFromFile(env, fullPath);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t\treturn { skills, diagnostics };\n\t}\n\n\tfor (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n\t\tif (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\t\tconst fullPath = entry.path;\n\t\tconst kind = await resolveKind(env, entry, diagnostics);\n\t\tif (!kind) continue;\n\n\t\tconst relPath = relativeEnvPath(rootDir, fullPath);\n\t\tconst ignorePath = kind === \"directory\" ? `${relPath}/` : relPath;\n\t\tif (ignoreMatcher.ignores(ignorePath)) continue;\n\n\t\tif (kind === \"directory\") {\n\t\t\tconst result = await loadSkillsFromDirInternal(env, fullPath, false, ignoreMatcher, rootDir);\n\t\t\tskills.push(...result.skills);\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (kind !== \"file\" || !includeRootFiles || !entry.name.endsWith(\".md\")) continue;\n\t\tconst result = await loadSkillFromFile(env, fullPath);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\n\treturn { skills, diagnostics };\n}\n\nasync function addIgnoreRules(\n\tenv: ExecutionEnv,\n\tig: IgnoreMatcher,\n\tdir: string,\n\trootDir: string,\n\tdiagnostics: SkillDiagnostic[],\n): Promise<void> {\n\tconst relativeDir = relativeEnvPath(rootDir, dir);\n\tconst prefix = relativeDir ? `${relativeDir}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = joinEnvPath(dir, filename);\n\t\tconst info = await env.fileInfo(ignorePath);\n\t\tif (!info.ok) {\n\t\t\tif (info.error.code !== \"not_found\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\t\tmessage: info.error.message,\n\t\t\t\t\tpath: ignorePath,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (info.value.kind !== \"file\") continue;\n\t\tconst content = await env.readTextFile(ignorePath);\n\t\tif (!content.ok) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"read_failed\", message: content.error.message, path: ignorePath });\n\t\t\tcontinue;\n\t\t}\n\t\tconst patterns = content.value\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t.filter((line): line is string => Boolean(line));\n\t\tif (patterns.length > 0) ig.add(patterns);\n\t}\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\tif (pattern.startsWith(\"/\")) pattern = pattern.slice(1);\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nasync function loadSkillFromFile(\n\tenv: ExecutionEnv,\n\tfilePath: string,\n): Promise<{ skill: Skill | null; diagnostics: SkillDiagnostic[] }> {\n\tconst diagnostics: SkillDiagnostic[] = [];\n\tconst rawContent = await env.readTextFile(filePath);\n\tif (!rawContent.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"read_failed\", message: rawContent.error.message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst parsed = parseFrontmatter<SkillFrontmatter>(rawContent.value);\n\tif (!parsed.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"parse_failed\", message: parsed.error.message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst { frontmatter, body } = parsed.value;\n\tconst skillDir = dirnameEnvPath(filePath);\n\tconst parentDirName = basenameEnvPath(skillDir);\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description : undefined;\n\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"invalid_metadata\", message: error, path: filePath });\n\t}\n\n\tconst frontmatterName = typeof frontmatter.name === \"string\" ? frontmatter.name : undefined;\n\tconst name = frontmatterName || parentDirName;\n\tfor (const error of validateName(name, parentDirName)) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"invalid_metadata\", message: error, path: filePath });\n\t}\n\n\tif (!description || description.trim() === \"\") {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\treturn {\n\t\tskill: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tcontent: body,\n\t\t\tfilePath,\n\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n\nfunction validateName(name: string, parentDirName: string): string[] {\n\tconst errors: string[] = [];\n\tif (name !== parentDirName) errors.push(`name \"${name}\" does not match parent directory \"${parentDirName}\"`);\n\tif (name.length > MAX_NAME_LENGTH) errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) errors.push(\"name must not start or end with a hyphen\");\n\tif (name.includes(\"--\")) errors.push(\"name must not contain consecutive hyphens\");\n\treturn errors;\n}\n\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction parseFrontmatter<T extends Record<string, unknown>>(\n\tcontent: string,\n): Result<{ frontmatter: T; body: string }, Error> {\n\ttry {\n\t\tconst normalized = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\t\tif (!normalized.startsWith(\"---\")) return { ok: true, value: { frontmatter: {} as T, body: normalized } };\n\t\tconst endIndex = normalized.indexOf(\"\\n---\", 3);\n\t\tif (endIndex === -1) return { ok: true, value: { frontmatter: {} as T, body: normalized } };\n\t\tconst yamlString = normalized.slice(4, endIndex);\n\t\tconst body = normalized.slice(endIndex + 4).trim();\n\t\treturn { ok: true, value: { frontmatter: (parse(yamlString) ?? {}) as T, body } };\n\t} catch (error) {\n\t\treturn { ok: false, error: toError(error) };\n\t}\n}\n\nasync function resolveKind(\n\tenv: ExecutionEnv,\n\tinfo: FileInfo,\n\tdiagnostics: SkillDiagnostic[],\n): Promise<\"file\" | \"directory\" | undefined> {\n\tif (info.kind === \"file\" || info.kind === \"directory\") return info.kind;\n\tconst canonicalPath = await env.canonicalPath(info.path);\n\tif (!canonicalPath.ok) {\n\t\tif (canonicalPath.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: canonicalPath.error.message,\n\t\t\t\tpath: info.path,\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst target = await env.fileInfo(canonicalPath.value);\n\tif (!target.ok) {\n\t\tif (target.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: target.error.message,\n\t\t\t\tpath: info.path,\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn target.value.kind === \"file\" || target.value.kind === \"directory\" ? target.value.kind : undefined;\n}\n\nfunction joinEnvPath(base: string, child: string): string {\n\treturn `${base.replace(/\\/+$/, \"\")}/${child.replace(/^\\/+/, \"\")}`;\n}\n\nfunction dirnameEnvPath(path: string): string {\n\tconst normalized = path.replace(/\\/+$/, \"\");\n\tconst slashIndex = normalized.lastIndexOf(\"/\");\n\treturn slashIndex <= 0 ? \"/\" : normalized.slice(0, slashIndex);\n}\n\nfunction basenameEnvPath(path: string): string {\n\tconst normalized = path.replace(/\\/+$/, \"\");\n\tconst slashIndex = normalized.lastIndexOf(\"/\");\n\treturn slashIndex === -1 ? normalized : normalized.slice(slashIndex + 1);\n}\n\nfunction relativeEnvPath(root: string, path: string): string {\n\tconst normalizedRoot = root.replace(/\\/+$/, \"\");\n\tconst normalizedPath = path.replace(/\\/+$/, \"\");\n\tif (normalizedPath === normalizedRoot) return \"\";\n\treturn normalizedPath.startsWith(`${normalizedRoot}/`)\n\t\t? normalizedPath.slice(normalizedRoot.length + 1)\n\t\t: normalizedPath.replace(/^\\/+/, \"\");\n}\n"]}
1
+ {"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../../src/harness/skills.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,YAAY,EAA8B,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAQhG,MAAM,MAAM,mBAAmB,GAC5B,kBAAkB,GAClB,aAAa,GACb,aAAa,GACb,cAAc,GACd,kBAAkB,CAAC;AAEtB,6CAA6C;AAC7C,MAAM,WAAW,eAAe;IAC/B,gEAAgE;IAChE,IAAI,EAAE,SAAS,CAAC;IAChB,8BAA8B;IAC9B,IAAI,EAAE,mBAAmB,CAAC;IAC1B,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAC;IAChB,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;CACb;AASD,2FAA2F;AAC3F,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,sBAAsB,CAAC,EAAE,MAAM,GAAG,MAAM,CAG3F;AAED;;;;;GAKG;AACH,wBAAsB,UAAU,CAC/B,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GACrB,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,EAAE,CAAC;IAAC,WAAW,EAAE,eAAe,EAAE,CAAA;CAAE,CAAC,CAuB9D;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,MAAM,SAAS,KAAK,GAAG,KAAK,EAC5E,GAAG,EAAE,YAAY,EACjB,MAAM,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC,EAChD,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,KAAK,MAAM,GAClD,OAAO,CAAC;IACV,MAAM,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IAClD,WAAW,EAAE,KAAK,CAAC,eAAe,GAAG;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAC1D,CAAC,CAWD","sourcesContent":["import ignore from \"ignore\";\nimport { parse } from \"yaml\";\nimport { type ExecutionEnv, type FileInfo, type Result, type Skill, toError } from \"./types.ts\";\n\nconst MAX_NAME_LENGTH = 64;\nconst MAX_DESCRIPTION_LENGTH = 1024;\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nexport type SkillDiagnosticCode =\n\t| \"file_info_failed\"\n\t| \"list_failed\"\n\t| \"read_failed\"\n\t| \"parse_failed\"\n\t| \"invalid_metadata\";\n\n/** Warning produced while loading skills. */\nexport interface SkillDiagnostic {\n\t/** Diagnostic severity. Currently only warnings are emitted. */\n\ttype: \"warning\";\n\t/** Stable diagnostic code. */\n\tcode: SkillDiagnosticCode;\n\t/** Human-readable diagnostic message. */\n\tmessage: string;\n\t/** Path associated with the diagnostic. */\n\tpath: string;\n}\n\ninterface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\n/** Format a skill invocation prompt, optionally appending additional user instructions. */\nexport function formatSkillInvocation(skill: Skill, additionalInstructions?: string): string {\n\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${dirnameEnvPath(skill.filePath)}.\\n\\n${skill.content}\\n</skill>`;\n\treturn additionalInstructions ? `${skillBlock}\\n\\n${additionalInstructions}` : skillBlock;\n}\n\n/**\n * Load skills from one or more directories.\n *\n * Traverses directories recursively, loads `SKILL.md` files, loads direct root `.md` files as skills, honors ignore files,\n * and returns diagnostics for invalid skill files. Missing input directories are skipped.\n */\nexport async function loadSkills(\n\tenv: ExecutionEnv,\n\tdirs: string | string[],\n): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[] }> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: SkillDiagnostic[] = [];\n\tfor (const dir of Array.isArray(dirs) ? dirs : [dirs]) {\n\t\tconst rootInfoResult = await env.fileInfo(dir);\n\t\tif (!rootInfoResult.ok) {\n\t\t\tif (rootInfoResult.error.code !== \"not_found\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\t\tmessage: rootInfoResult.error.message,\n\t\t\t\t\tpath: dir,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst rootInfo = rootInfoResult.value;\n\t\tif ((await resolveKind(env, rootInfo, diagnostics)) !== \"directory\") continue;\n\t\tconst result = await loadSkillsFromDirInternal(env, rootInfo.path, true, ignore(), rootInfo.path);\n\t\tskills.push(...result.skills);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\treturn { skills, diagnostics };\n}\n\n/**\n * Load skills from source-tagged directories.\n *\n * Source values are preserved exactly and attached to every loaded skill and diagnostic. The agent package does not\n * interpret source values; applications define their own provenance shape.\n */\nexport async function loadSourcedSkills<TSource, TSkill extends Skill = Skill>(\n\tenv: ExecutionEnv,\n\tinputs: Array<{ path: string; source: TSource }>,\n\tmapSkill?: (skill: Skill, source: TSource) => TSkill,\n): Promise<{\n\tskills: Array<{ skill: TSkill; source: TSource }>;\n\tdiagnostics: Array<SkillDiagnostic & { source: TSource }>;\n}> {\n\tconst skills: Array<{ skill: TSkill; source: TSource }> = [];\n\tconst diagnostics: Array<SkillDiagnostic & { source: TSource }> = [];\n\tfor (const input of inputs) {\n\t\tconst result = await loadSkills(env, input.path);\n\t\tfor (const skill of result.skills) {\n\t\t\tskills.push({ skill: mapSkill ? mapSkill(skill, input.source) : (skill as TSkill), source: input.source });\n\t\t}\n\t\tfor (const diagnostic of result.diagnostics) diagnostics.push({ ...diagnostic, source: input.source });\n\t}\n\treturn { skills, diagnostics };\n}\n\nasync function loadSkillsFromDirInternal(\n\tenv: ExecutionEnv,\n\tdir: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher: IgnoreMatcher,\n\trootDir: string,\n): Promise<{ skills: Skill[]; diagnostics: SkillDiagnostic[] }> {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: SkillDiagnostic[] = [];\n\n\tconst dirInfoResult = await env.fileInfo(dir);\n\tif (!dirInfoResult.ok) {\n\t\tif (dirInfoResult.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: dirInfoResult.error.message,\n\t\t\t\tpath: dir,\n\t\t\t});\n\t\t}\n\t\treturn { skills, diagnostics };\n\t}\n\tconst dirInfo = dirInfoResult.value;\n\tif ((await resolveKind(env, dirInfo, diagnostics)) !== \"directory\") return { skills, diagnostics };\n\n\tawait addIgnoreRules(env, ignoreMatcher, dir, rootDir, diagnostics);\n\n\tconst entriesResult = await env.listDir(dir);\n\tif (!entriesResult.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"list_failed\", message: entriesResult.error.message, path: dir });\n\t\treturn { skills, diagnostics };\n\t}\n\tconst entries = entriesResult.value;\n\n\tfor (const entry of entries) {\n\t\tif (entry.name !== \"SKILL.md\") continue;\n\t\tconst fullPath = entry.path;\n\t\tconst kind = await resolveKind(env, entry, diagnostics);\n\t\tif (kind !== \"file\") continue;\n\t\tconst relPath = relativeEnvPath(rootDir, fullPath);\n\t\tif (ignoreMatcher.ignores(relPath)) continue;\n\n\t\tconst result = await loadSkillFromFile(env, fullPath);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t\treturn { skills, diagnostics };\n\t}\n\n\tfor (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n\t\tif (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\t\tconst fullPath = entry.path;\n\t\tconst kind = await resolveKind(env, entry, diagnostics);\n\t\tif (!kind) continue;\n\n\t\tconst relPath = relativeEnvPath(rootDir, fullPath);\n\t\tconst ignorePath = kind === \"directory\" ? `${relPath}/` : relPath;\n\t\tif (ignoreMatcher.ignores(ignorePath)) continue;\n\n\t\tif (kind === \"directory\") {\n\t\t\tconst result = await loadSkillsFromDirInternal(env, fullPath, false, ignoreMatcher, rootDir);\n\t\t\tskills.push(...result.skills);\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (kind !== \"file\" || !includeRootFiles || !entry.name.endsWith(\".md\")) continue;\n\t\tconst result = await loadSkillFromFile(env, fullPath);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\n\treturn { skills, diagnostics };\n}\n\nasync function addIgnoreRules(\n\tenv: ExecutionEnv,\n\tig: IgnoreMatcher,\n\tdir: string,\n\trootDir: string,\n\tdiagnostics: SkillDiagnostic[],\n): Promise<void> {\n\tconst relativeDir = relativeEnvPath(rootDir, dir);\n\tconst prefix = relativeDir ? `${relativeDir}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = joinEnvPath(dir, filename);\n\t\tconst info = await env.fileInfo(ignorePath);\n\t\tif (!info.ok) {\n\t\t\tif (info.error.code !== \"not_found\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\t\tmessage: info.error.message,\n\t\t\t\t\tpath: ignorePath,\n\t\t\t\t});\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (info.value.kind !== \"file\") continue;\n\t\tconst content = await env.readTextFile(ignorePath);\n\t\tif (!content.ok) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"read_failed\", message: content.error.message, path: ignorePath });\n\t\t\tcontinue;\n\t\t}\n\t\tconst patterns = content.value\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t.filter((line): line is string => Boolean(line));\n\t\tif (patterns.length > 0) ig.add(patterns);\n\t}\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\tif (pattern.startsWith(\"/\")) pattern = pattern.slice(1);\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nasync function loadSkillFromFile(\n\tenv: ExecutionEnv,\n\tfilePath: string,\n): Promise<{ skill: Skill | null; diagnostics: SkillDiagnostic[] }> {\n\tconst diagnostics: SkillDiagnostic[] = [];\n\tconst rawContent = await env.readTextFile(filePath);\n\tif (!rawContent.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"read_failed\", message: rawContent.error.message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst parsed = parseFrontmatter<SkillFrontmatter>(rawContent.value);\n\tif (!parsed.ok) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"parse_failed\", message: parsed.error.message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst { frontmatter, body } = parsed.value;\n\tconst skillDir = dirnameEnvPath(filePath);\n\tconst parentDirName = basenameEnvPath(skillDir);\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description : undefined;\n\n\tfor (const error of validateDescription(description)) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"invalid_metadata\", message: error, path: filePath });\n\t}\n\n\tconst frontmatterName = typeof frontmatter.name === \"string\" ? frontmatter.name : undefined;\n\tconst name = frontmatterName || parentDirName;\n\tfor (const error of validateName(name, parentDirName)) {\n\t\tdiagnostics.push({ type: \"warning\", code: \"invalid_metadata\", message: error, path: filePath });\n\t}\n\n\tif (!description || description.trim() === \"\") {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\treturn {\n\t\tskill: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tcontent: body,\n\t\t\tfilePath,\n\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n\nfunction validateName(name: string, parentDirName: string): string[] {\n\tconst errors: string[] = [];\n\tif (name !== parentDirName) errors.push(`name \"${name}\" does not match parent directory \"${parentDirName}\"`);\n\tif (name.length > MAX_NAME_LENGTH) errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(\"name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)\");\n\t}\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) errors.push(\"name must not start or end with a hyphen\");\n\tif (name.includes(\"--\")) errors.push(\"name must not contain consecutive hyphens\");\n\treturn errors;\n}\n\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\treturn errors;\n}\n\nfunction parseFrontmatter<T extends Record<string, unknown>>(\n\tcontent: string,\n): Result<{ frontmatter: T; body: string }, Error> {\n\ttry {\n\t\tconst normalized = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\t\tif (!normalized.startsWith(\"---\")) return { ok: true, value: { frontmatter: {} as T, body: normalized } };\n\t\tconst endIndex = normalized.indexOf(\"\\n---\", 3);\n\t\tif (endIndex === -1) return { ok: true, value: { frontmatter: {} as T, body: normalized } };\n\t\tconst yamlString = normalized.slice(4, endIndex);\n\t\tconst body = normalized.slice(endIndex + 4).trim();\n\t\treturn { ok: true, value: { frontmatter: (parse(yamlString) ?? {}) as T, body } };\n\t} catch (error) {\n\t\treturn { ok: false, error: toError(error) };\n\t}\n}\n\nasync function resolveKind(\n\tenv: ExecutionEnv,\n\tinfo: FileInfo,\n\tdiagnostics: SkillDiagnostic[],\n): Promise<\"file\" | \"directory\" | undefined> {\n\tif (info.kind === \"file\" || info.kind === \"directory\") return info.kind;\n\tconst canonicalPath = await env.canonicalPath(info.path);\n\tif (!canonicalPath.ok) {\n\t\tif (canonicalPath.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: canonicalPath.error.message,\n\t\t\t\tpath: info.path,\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n\tconst target = await env.fileInfo(canonicalPath.value);\n\tif (!target.ok) {\n\t\tif (target.error.code !== \"not_found\") {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"file_info_failed\",\n\t\t\t\tmessage: target.error.message,\n\t\t\t\tpath: info.path,\n\t\t\t});\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn target.value.kind === \"file\" || target.value.kind === \"directory\" ? target.value.kind : undefined;\n}\n\nfunction joinEnvPath(base: string, child: string): string {\n\treturn `${base.replace(/\\/+$/, \"\")}/${child.replace(/^\\/+/, \"\")}`;\n}\n\nfunction dirnameEnvPath(path: string): string {\n\tconst normalized = path.replace(/\\/+$/, \"\");\n\tconst slashIndex = normalized.lastIndexOf(\"/\");\n\treturn slashIndex <= 0 ? \"/\" : normalized.slice(0, slashIndex);\n}\n\nfunction basenameEnvPath(path: string): string {\n\tconst normalized = path.replace(/\\/+$/, \"\");\n\tconst slashIndex = normalized.lastIndexOf(\"/\");\n\treturn slashIndex === -1 ? normalized : normalized.slice(slashIndex + 1);\n}\n\nfunction relativeEnvPath(root: string, path: string): string {\n\tconst normalizedRoot = root.replace(/\\/+$/, \"\");\n\tconst normalizedPath = path.replace(/\\/+$/, \"\");\n\tif (normalizedPath === normalizedRoot) return \"\";\n\treturn normalizedPath.startsWith(`${normalizedRoot}/`)\n\t\t? normalizedPath.slice(normalizedRoot.length + 1)\n\t\t: normalizedPath.replace(/^\\/+/, \"\");\n}\n"]}