@geminixiang/mikan 0.5.3 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +2 -2
  3. package/dist/adapter.d.ts +1 -1
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/adapter.js.map +1 -1
  6. package/dist/agent.d.ts +10 -1
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.js +153 -95
  9. package/dist/agent.js.map +1 -1
  10. package/dist/commands/model.d.ts +2 -2
  11. package/dist/commands/model.d.ts.map +1 -1
  12. package/dist/commands/model.js.map +1 -1
  13. package/dist/commands/registry.d.ts.map +1 -1
  14. package/dist/commands/registry.js +2 -5
  15. package/dist/commands/registry.js.map +1 -1
  16. package/dist/config.d.ts +33 -0
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/config.js +83 -5
  19. package/dist/config.js.map +1 -1
  20. package/dist/execution-resolver.d.ts.map +1 -1
  21. package/dist/execution-resolver.js +2 -3
  22. package/dist/execution-resolver.js.map +1 -1
  23. package/dist/harness/auth.d.ts +16 -0
  24. package/dist/harness/auth.d.ts.map +1 -0
  25. package/dist/harness/auth.js +86 -0
  26. package/dist/harness/auth.js.map +1 -0
  27. package/dist/harness/extensions/loader.d.ts +43 -0
  28. package/dist/harness/extensions/loader.d.ts.map +1 -0
  29. package/dist/harness/extensions/loader.js +325 -0
  30. package/dist/harness/extensions/loader.js.map +1 -0
  31. package/dist/harness/extensions/registry.d.ts +23 -0
  32. package/dist/harness/extensions/registry.d.ts.map +1 -0
  33. package/dist/harness/extensions/registry.js +45 -0
  34. package/dist/harness/extensions/registry.js.map +1 -0
  35. package/dist/harness/extensions/types.d.ts +225 -0
  36. package/dist/harness/extensions/types.d.ts.map +1 -0
  37. package/dist/harness/extensions/types.js +2 -0
  38. package/dist/harness/extensions/types.js.map +1 -0
  39. package/dist/harness/http.d.ts +16 -0
  40. package/dist/harness/http.d.ts.map +1 -0
  41. package/dist/harness/http.js +71 -0
  42. package/dist/harness/http.js.map +1 -0
  43. package/dist/harness/index.d.ts +19 -0
  44. package/dist/harness/index.d.ts.map +1 -0
  45. package/dist/harness/index.js +18 -0
  46. package/dist/harness/index.js.map +1 -0
  47. package/dist/harness/models.d.ts +34 -0
  48. package/dist/harness/models.d.ts.map +1 -0
  49. package/dist/harness/models.js +248 -0
  50. package/dist/harness/models.js.map +1 -0
  51. package/dist/harness/runner.d.ts +124 -0
  52. package/dist/harness/runner.d.ts.map +1 -0
  53. package/dist/harness/runner.js +436 -0
  54. package/dist/harness/runner.js.map +1 -0
  55. package/dist/harness/session-store.d.ts +77 -0
  56. package/dist/harness/session-store.d.ts.map +1 -0
  57. package/dist/harness/session-store.js +248 -0
  58. package/dist/harness/session-store.js.map +1 -0
  59. package/dist/harness/settings.d.ts +47 -0
  60. package/dist/harness/settings.d.ts.map +1 -0
  61. package/dist/harness/settings.js +29 -0
  62. package/dist/harness/settings.js.map +1 -0
  63. package/dist/harness/skills.d.ts +54 -0
  64. package/dist/harness/skills.d.ts.map +1 -0
  65. package/dist/harness/skills.js +203 -0
  66. package/dist/harness/skills.js.map +1 -0
  67. package/dist/harness/types.d.ts +32 -0
  68. package/dist/harness/types.d.ts.map +1 -0
  69. package/dist/harness/types.js +2 -0
  70. package/dist/harness/types.js.map +1 -0
  71. package/dist/index.d.ts +1 -0
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1 -0
  74. package/dist/index.js.map +1 -1
  75. package/dist/main.js +65 -3
  76. package/dist/main.js.map +1 -1
  77. package/dist/model-registry.d.ts +2 -2
  78. package/dist/model-registry.d.ts.map +1 -1
  79. package/dist/model-registry.js.map +1 -1
  80. package/dist/runtime/conversation-runtime.js +1 -1
  81. package/dist/runtime/conversation-runtime.js.map +1 -1
  82. package/dist/runtime/types.d.ts +3 -1
  83. package/dist/runtime/types.d.ts.map +1 -1
  84. package/dist/runtime/types.js.map +1 -1
  85. package/dist/sessions/agent-memory-file-manager.d.ts.map +1 -1
  86. package/dist/sessions/agent-memory-file-manager.js +8 -8
  87. package/dist/sessions/agent-memory-file-manager.js.map +1 -1
  88. package/dist/sessions/metadata.js +2 -2
  89. package/dist/sessions/metadata.js.map +1 -1
  90. package/dist/sessions/store.d.ts +3 -3
  91. package/dist/sessions/store.d.ts.map +1 -1
  92. package/dist/sessions/store.js +4 -4
  93. package/dist/sessions/store.js.map +1 -1
  94. package/dist/sessions/types.d.ts +1 -1
  95. package/dist/sessions/types.d.ts.map +1 -1
  96. package/dist/sessions/types.js.map +1 -1
  97. package/dist/trigger.d.ts.map +1 -1
  98. package/dist/trigger.js +5 -13
  99. package/dist/trigger.js.map +1 -1
  100. package/dist/types.d.ts +6 -0
  101. package/dist/types.d.ts.map +1 -1
  102. package/dist/types.js.map +1 -1
  103. package/dist/vault/index.d.ts.map +1 -1
  104. package/dist/vault/index.js +7 -1
  105. package/dist/vault/index.js.map +1 -1
  106. package/dist/web/admin/portal.d.ts.map +1 -1
  107. package/dist/web/admin/portal.js +328 -9
  108. package/dist/web/admin/portal.js.map +1 -1
  109. package/dist/web/admin/provider-models.d.ts +2 -2
  110. package/dist/web/admin/provider-models.d.ts.map +1 -1
  111. package/dist/web/admin/provider-models.js.map +1 -1
  112. package/dist/web/session-view/service.js +5 -5
  113. package/dist/web/session-view/service.js.map +1 -1
  114. package/package.json +3 -3
@@ -85,7 +85,7 @@ export class AgentMemoryFileManager {
85
85
  const existing = tryResolveCurrentSession(options.sessionDir);
86
86
  if (existing && !isPlatformHistorySession(existing)) {
87
87
  if (!options.rotateTopLevelSession || !shouldRotateTopLevelSession(existing, this.now())) {
88
- syncSessionFromLog(existing, options.sessionDir, options.cwd, selectExistingSessionSyncMessages(records, {
88
+ syncSessionFromLog(existing, options.cwd, selectExistingSessionSyncMessages(records, {
89
89
  sessionKey: null,
90
90
  excludeMessageId: options.currentMessageId,
91
91
  }), this.historyWindow());
@@ -99,7 +99,7 @@ export class AgentMemoryFileManager {
99
99
  now: this.now(),
100
100
  excludeMessageId: options.currentMessageId,
101
101
  });
102
- bootstrapSessionFromLog(sessionFile, options.sessionDir, options.cwd, bootstrapRecords, latestSyncMessageId(records, {
102
+ bootstrapSessionFromLog(sessionFile, options.cwd, bootstrapRecords, latestSyncMessageId(records, {
103
103
  sessionKey: null,
104
104
  excludeMessageId: options.currentMessageId,
105
105
  }));
@@ -115,7 +115,7 @@ export class AgentMemoryFileManager {
115
115
  const threadRootMessage = buildThreadRootSeed(findLogRecordById(records, threadId)?.message);
116
116
  const existing = tryResolveThreadSession(threadFile);
117
117
  if (existing) {
118
- syncSessionFromLog(existing, options.sessionDir, options.cwd, selectExistingSessionSyncMessages(records, {
118
+ syncSessionFromLog(existing, options.cwd, selectExistingSessionSyncMessages(records, {
119
119
  sessionKey: options.sessionKey,
120
120
  excludeMessageId: options.currentMessageId,
121
121
  }), this.historyWindow());
@@ -128,7 +128,7 @@ export class AgentMemoryFileManager {
128
128
  now: this.now(),
129
129
  excludeMessageId: options.currentMessageId,
130
130
  });
131
- bootstrapSessionFromLog(threadFile, options.sessionDir, options.cwd, bootstrapRecords, latestSyncMessageId(records, {
131
+ bootstrapSessionFromLog(threadFile, options.cwd, bootstrapRecords, latestSyncMessageId(records, {
132
132
  sessionKey: options.sessionKey,
133
133
  excludeMessageId: options.currentMessageId,
134
134
  }));
@@ -296,10 +296,10 @@ function sortTime(record) {
296
296
  }
297
297
  return record.index;
298
298
  }
299
- function bootstrapSessionFromLog(sessionFile, sessionDir, cwd, records, lastMessageId = records.at(-1)?.message.ts) {
299
+ function bootstrapSessionFromLog(sessionFile, cwd, records, lastMessageId = records.at(-1)?.message.ts) {
300
300
  if (records.length === 0 && !lastMessageId)
301
301
  return;
302
- const sessionManager = openManagedSession(sessionFile, sessionDir, cwd);
302
+ const sessionManager = openManagedSession(sessionFile, cwd);
303
303
  appendLogRecordsToSession(sessionManager, records);
304
304
  sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {
305
305
  source: "log.jsonl",
@@ -308,10 +308,10 @@ function bootstrapSessionFromLog(sessionFile, sessionDir, cwd, records, lastMess
308
308
  });
309
309
  forceRewriteSession(sessionManager, sessionFile);
310
310
  }
311
- function syncSessionFromLog(sessionFile, sessionDir, cwd, records, historyWindow) {
311
+ function syncSessionFromLog(sessionFile, cwd, records, historyWindow) {
312
312
  if (records.length === 0)
313
313
  return;
314
- syncSessionManagerFromLog(openManagedSession(sessionFile, sessionDir, cwd), records, historyWindow);
314
+ syncSessionManagerFromLog(openManagedSession(sessionFile, cwd), records, historyWindow);
315
315
  }
316
316
  function syncSessionManagerFromLog(sessionManager, records, historyWindow) {
317
317
  if (records.length === 0)
@@ -1 +1 @@
1
- {"version":3,"file":"agent-memory-file-manager.js","sourceRoot":"","sources":["../../src/sessions/agent-memory-file-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAC9B,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,GAGxB,MAAM,YAAY,CAAC;AAEpB,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAChD,MAAM,wBAAwB,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC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,QAAQ,IAAI,OAAO,CAAC,IAAI,IAAI,SAAS,CAAC;IAChE,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,oBAAoB,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACrF,OAAO,SAAS,CAAC,CAAC,CAAC,IAAI,SAAS,MAAM,SAAS,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,SAAS,MAAM,IAAI,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,SAAS;IAChB,OAAO;QACL,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;KACrE,CAAC;AACJ,CAAC","sourcesContent":["import { SessionManager, type SessionEntry } from \"@earendil-works/pi-coding-agent\";\nimport { join } from \"path\";\nimport type { ConversationLogMessage } from \"../types.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { formatLocalTimestamp } from \"../utils/date.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport * as log from \"../log.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nimport {\n createManagedSessionFile,\n createManagedSessionFileAtPath,\n extractSessionSuffix,\n getChannelSessionDir,\n getThreadSessionFile,\n openManagedSession,\n resolveChannelSessionFile,\n tryResolveCurrentSession,\n tryResolveThreadSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./store.js\";\n\nconst DEFAULT_RECENT_DAYS = 14;\nconst DEFAULT_MAX_TOP_LEVEL_MESSAGES = 200;\nconst CHAT_SYNC_CUSTOM_TYPE = \"mikan.chat_sync\";\nconst BIWEEKLY_ROTATION_ANCHOR = new Date(2026, 0, 4); // Sunday\nconst BIWEEKLY_MS = 14 * 24 * 60 * 60 * 1000;\n\ntype SessionAppendMessage = Parameters<SessionManager[\"appendMessage\"]>[0];\n\ninterface LogRecord {\n message: ConversationLogMessage;\n index: number;\n}\n\nexport type {\n AgentMemoryFileManagerOptions,\n HasMaterializedSessionOptions,\n RegisterThreadSessionOptions,\n ResetChatSessionOptions,\n ResolveChatSessionScopeOptions,\n SyncAgentMemoryFileManagerOptions,\n ThreadBootstrapWaitOptions,\n} from \"./types.js\";\nimport type {\n AgentMemoryFileManagerOptions,\n HasMaterializedSessionOptions,\n RegisterThreadSessionOptions,\n ResetChatSessionOptions,\n ResolveChatSessionScopeOptions,\n SyncAgentMemoryFileManagerOptions,\n ThreadBootstrapWaitOptions,\n} from \"./types.js\";\n\nexport function hasMaterializedChatSession(options: HasMaterializedSessionOptions): boolean {\n if (!options.sessionKey.includes(\":\")) {\n return resolveChannelSessionFile(options.conversationDir) !== null;\n }\n return (\n tryResolveThreadSession(getThreadSessionFile(options.conversationDir, options.sessionKey)) !==\n null\n );\n}\n\nexport function registerThreadSession(options: RegisterThreadSessionOptions): string | null {\n if (!options.sessionKey.includes(\":\")) return null;\n\n const threadFile = getThreadSessionFile(options.conversationDir, options.sessionKey);\n return (\n tryResolveThreadSession(threadFile) ??\n createManagedSessionFileAtPath(threadFile, options.cwd ?? options.conversationDir)\n );\n}\n\nexport async function waitForThreadSessionBootstrap(\n options: ThreadBootstrapWaitOptions,\n): Promise<boolean> {\n const {\n parentSessionKey,\n sessionKey,\n hasThreadSession,\n isParentRunning,\n sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n pollMs = 100,\n } = options;\n\n if (!sessionKey.includes(\":\")) return false;\n if (sessionKey === parentSessionKey) return false;\n if (hasThreadSession()) return false;\n\n let waited = false;\n while (isParentRunning() && !hasThreadSession()) {\n waited = true;\n await sleep(pollMs);\n }\n\n return waited;\n}\n\nexport class AgentMemoryFileManager {\n private readonly recentDays: number;\n private readonly maxTopLevelMessages: number;\n private readonly now: () => Date;\n\n constructor(options: AgentMemoryFileManagerOptions = {}) {\n this.recentDays = options.recentDays ?? DEFAULT_RECENT_DAYS;\n this.maxTopLevelMessages = options.maxTopLevelMessages ?? DEFAULT_MAX_TOP_LEVEL_MESSAGES;\n this.now = options.now ?? (() => new Date());\n }\n\n async resolveSessionScope(\n options: ResolveChatSessionScopeOptions,\n ): Promise<ResolvedSessionScope> {\n const cwd = options.cwd ?? options.conversationDir;\n const sessionDir = getChannelSessionDir(options.conversationDir);\n\n if (!options.sessionKey.includes(\":\")) {\n const contextFile = this.resolveTopLevelSessionFile({\n conversationDir: options.conversationDir,\n sessionDir,\n cwd,\n currentMessageId: options.currentMessageId,\n rotateTopLevelSession: options.rotateTopLevelSession === true,\n });\n return { sessionDir, contextFile, threadRootMessage: null };\n }\n\n return this.resolveThreadSessionScope({\n conversationDir: options.conversationDir,\n sessionDir,\n sessionKey: options.sessionKey,\n cwd,\n currentMessageId: options.currentMessageId,\n });\n }\n\n syncSessionManager(options: SyncAgentMemoryFileManagerOptions): void {\n const records = readConversationLog(options.conversationDir);\n syncSessionManagerFromLog(\n options.sessionManager,\n selectExistingSessionSyncMessages(records, {\n sessionKey: options.sessionKey.includes(\":\") ? options.sessionKey : null,\n excludeMessageId: options.currentMessageId,\n }),\n this.historyWindow(),\n );\n }\n\n resetSession(options: ResetChatSessionOptions): string {\n const cwd = options.cwd ?? options.conversationDir;\n if (options.sessionKey.includes(\":\")) {\n return createManagedSessionFileAtPath(\n getThreadSessionFile(options.conversationDir, options.sessionKey),\n cwd,\n );\n }\n\n return createManagedSessionFile(getChannelSessionDir(options.conversationDir), cwd);\n }\n\n private resolveTopLevelSessionFile(options: {\n conversationDir: string;\n sessionDir: string;\n cwd: string;\n currentMessageId?: string;\n rotateTopLevelSession: boolean;\n }): string {\n const records = readConversationLog(options.conversationDir);\n const existing = tryResolveCurrentSession(options.sessionDir);\n if (existing && !isPlatformHistorySession(existing)) {\n if (!options.rotateTopLevelSession || !shouldRotateTopLevelSession(existing, this.now())) {\n syncSessionFromLog(\n existing,\n options.sessionDir,\n options.cwd,\n selectExistingSessionSyncMessages(records, {\n sessionKey: null,\n excludeMessageId: options.currentMessageId,\n }),\n this.historyWindow(),\n );\n return existing;\n }\n }\n\n const sessionFile = createManagedSessionFile(options.sessionDir, options.cwd);\n const bootstrapRecords = selectRecentTopLevelMessages(records, {\n recentDays: this.recentDays,\n maxMessages: this.maxTopLevelMessages,\n now: this.now(),\n excludeMessageId: options.currentMessageId,\n });\n bootstrapSessionFromLog(\n sessionFile,\n options.sessionDir,\n options.cwd,\n bootstrapRecords,\n latestSyncMessageId(records, {\n sessionKey: null,\n excludeMessageId: options.currentMessageId,\n }),\n );\n return sessionFile;\n }\n\n private historyWindow(): HistoryWindow {\n return { recentDays: this.recentDays, maxMessages: this.maxTopLevelMessages, now: this.now() };\n }\n\n private resolveThreadSessionScope(options: {\n conversationDir: string;\n sessionDir: string;\n sessionKey: string;\n cwd: string;\n currentMessageId?: string;\n }): ResolvedSessionScope {\n const threadFile = getThreadSessionFile(options.conversationDir, options.sessionKey);\n const threadId = extractSessionSuffix(options.sessionKey);\n const records = readConversationLog(options.conversationDir);\n const threadRootMessage = buildThreadRootSeed(findLogRecordById(records, threadId)?.message);\n const existing = tryResolveThreadSession(threadFile);\n if (existing) {\n syncSessionFromLog(\n existing,\n options.sessionDir,\n options.cwd,\n selectExistingSessionSyncMessages(records, {\n sessionKey: options.sessionKey,\n excludeMessageId: options.currentMessageId,\n }),\n this.historyWindow(),\n );\n return { sessionDir: options.sessionDir, contextFile: existing, threadRootMessage };\n }\n\n createManagedSessionFileAtPath(threadFile, options.cwd);\n const bootstrapRecords = selectThreadBootstrapMessages(records, threadId, {\n recentDays: this.recentDays,\n maxTopLevelMessages: this.maxTopLevelMessages,\n now: this.now(),\n excludeMessageId: options.currentMessageId,\n });\n bootstrapSessionFromLog(\n threadFile,\n options.sessionDir,\n options.cwd,\n bootstrapRecords,\n latestSyncMessageId(records, {\n sessionKey: options.sessionKey,\n excludeMessageId: options.currentMessageId,\n }),\n );\n\n return { sessionDir: options.sessionDir, contextFile: threadFile, threadRootMessage };\n }\n}\n\nfunction shouldRotateTopLevelSession(sessionFile: string, now: Date): boolean {\n const timestamp = readSessionTimestamp(sessionFile);\n return timestamp !== null && biweeklyBucket(timestamp) !== biweeklyBucket(now);\n}\n\nfunction readSessionTimestamp(sessionFile: string): Date | null {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return null;\n const firstLine = raw.split(\"\\n\").find((line) => line.trim());\n if (!firstLine) return null;\n try {\n const header = parseJsonValue(\n firstLine,\n (value): value is { timestamp?: unknown } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n if (typeof header.timestamp !== \"string\") return null;\n const date = new Date(header.timestamp);\n return Number.isFinite(date.getTime()) ? date : null;\n } catch {\n return null;\n }\n}\n\nfunction biweeklyBucket(date: Date): number {\n const weekStart = sundayStart(date).getTime();\n const anchor = sundayStart(BIWEEKLY_ROTATION_ANCHOR).getTime();\n return Math.floor((weekStart - anchor) / BIWEEKLY_MS);\n}\n\nfunction sundayStart(date: Date): Date {\n return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());\n}\n\nfunction readConversationLog(conversationDir: string): LogRecord[] {\n const logFile = join(conversationDir, \"log.jsonl\");\n const raw = readTextFileIfExists(logFile);\n if (raw === undefined) return [];\n\n const lines = raw.trim().split(\"\\n\").filter(Boolean);\n const records: LogRecord[] = [];\n for (let i = 0; i < lines.length; i++) {\n try {\n const message = parseJsonValue(\n lines[i],\n (value): value is ConversationLogMessage => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n records.push({ message, index: i });\n } catch (err) {\n log.logWarning(\n `Skipping malformed log entry at ${logFile}:${i + 1}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n return coalesceMessagingBotLogChunks(records);\n}\n\nfunction coalesceMessagingBotLogChunks(records: LogRecord[]): LogRecord[] {\n const coalesced: LogRecord[] = [];\n for (const record of records) {\n const previous = coalesced.at(-1);\n if (previous && canCoalesceMessagingBotLogChunk(previous.message, record.message)) {\n previous.message.text = `${previous.message.text ?? \"\"}${record.message.text ?? \"\"}`;\n continue;\n }\n coalesced.push({ ...record, message: { ...record.message } });\n }\n return coalesced;\n}\n\nfunction canCoalesceMessagingBotLogChunk(\n previous: ConversationLogMessage,\n current: ConversationLogMessage,\n): boolean {\n return (\n previous.isMessagingBot === true &&\n current.isMessagingBot === true &&\n !!previous.ts &&\n previous.ts === current.ts &&\n previous.threadTs === current.threadTs &&\n previous.user === current.user\n );\n}\n\nfunction findLogRecordById(records: LogRecord[], messageId: string): LogRecord | undefined {\n for (let i = records.length - 1; i >= 0; i--) {\n if (records[i].message.ts === messageId) return records[i];\n }\n return undefined;\n}\n\nfunction selectRecentTopLevelMessages(\n records: LogRecord[],\n options: {\n recentDays: number;\n maxMessages: number;\n now: Date;\n excludeMessageId?: string;\n },\n): LogRecord[] {\n return selectRecentMessages(\n records.filter((record) => isTopLevelHistoryMessage(record.message, options.excludeMessageId)),\n options,\n );\n}\n\nfunction selectRecentMessages(records: LogRecord[], options: HistoryWindow): LogRecord[] {\n const sinceMs = options.now.getTime() - options.recentDays * 24 * 60 * 60 * 1000;\n return records\n .filter((record) => isRecentHistoryMessage(record.message, sinceMs))\n .slice(-options.maxMessages);\n}\n\nfunction selectThreadBootstrapMessages(\n records: LogRecord[],\n threadId: string,\n options: {\n recentDays: number;\n maxTopLevelMessages: number;\n now: Date;\n excludeMessageId?: string;\n },\n): LogRecord[] {\n const rootRecord = findLogRecordById(records, threadId);\n const topLevelSource = rootRecord\n ? records.filter((record) => record.index <= rootRecord.index)\n : records;\n const topLevelRecords = selectRecentTopLevelMessages(topLevelSource, {\n recentDays: options.recentDays,\n maxMessages: options.maxTopLevelMessages,\n now: options.now,\n excludeMessageId: options.excludeMessageId,\n });\n const threadRecords = records.filter(\n (record) =>\n isRenderableConversationMessage(record.message, options.excludeMessageId) &&\n (record.message.ts === threadId || record.message.threadTs === threadId),\n );\n\n return dedupeAndSortRecords([...topLevelRecords, ...threadRecords]);\n}\n\nfunction isTopLevelHistoryMessage(\n message: ConversationLogMessage,\n excludeMessageId?: string,\n): boolean {\n if (!isRenderableConversationMessage(message, excludeMessageId)) return false;\n return !message.threadTs;\n}\n\nfunction isRecentHistoryMessage(message: ConversationLogMessage, sinceMs: number): boolean {\n if (!message.date) return true;\n const dateMs = new Date(message.date).getTime();\n return !Number.isFinite(dateMs) || dateMs >= sinceMs;\n}\n\nfunction selectExistingSessionSyncMessages(\n records: LogRecord[],\n options: { sessionKey: string | null; excludeMessageId?: string },\n): LogRecord[] {\n const threadId = options.sessionKey ? extractSessionSuffix(options.sessionKey) : null;\n return dedupeAndSortRecords(\n records.filter((record) => {\n if (!isRenderableConversationMessage(record.message, options.excludeMessageId)) return false;\n if (!threadId) return !record.message.threadTs;\n return record.message.ts === threadId || record.message.threadTs === threadId;\n }),\n );\n}\n\nfunction latestSyncMessageId(\n records: LogRecord[],\n options: { sessionKey: string | null; excludeMessageId?: string },\n): string | undefined {\n return selectExistingSessionSyncMessages(records, options).at(-1)?.message.ts;\n}\n\nfunction isRenderableConversationMessage(\n message: ConversationLogMessage,\n excludeMessageId?: string,\n): boolean {\n if (excludeMessageId && message.ts === excludeMessageId) return false;\n if (isChatCommandMessage(message)) return false;\n return !!message.text?.trim();\n}\n\nfunction isChatCommandMessage(message: ConversationLogMessage): boolean {\n const text = message.text?.trim() ?? \"\";\n return (\n !message.isMessagingBot &&\n /^\\/(?:pi-[\\w-]+|login|session|new|stop|model|sandbox|admin|auto-reply)(?:@\\w+)?(?:\\s|$)/i.test(\n text,\n )\n );\n}\n\nfunction dedupeAndSortRecords(records: LogRecord[]): LogRecord[] {\n const byKey = new Map<string, LogRecord>();\n for (const record of records) {\n byKey.set(record.message.ts ?? `line:${record.index}`, record);\n }\n\n return Array.from(byKey.values()).toSorted((a, b) => {\n const aTime = sortTime(a);\n const bTime = sortTime(b);\n if (aTime !== bTime) return aTime - bTime;\n return a.index - b.index;\n });\n}\n\nfunction sortTime(record: LogRecord): number {\n if (record.message.date) {\n const dateMs = new Date(record.message.date).getTime();\n if (Number.isFinite(dateMs)) return dateMs;\n }\n\n if (record.message.ts) {\n const tsMs = Number(record.message.ts) * 1000;\n if (Number.isFinite(tsMs)) return tsMs;\n }\n\n return record.index;\n}\n\nfunction bootstrapSessionFromLog(\n sessionFile: string,\n sessionDir: string,\n cwd: string,\n records: LogRecord[],\n lastMessageId = records.at(-1)?.message.ts,\n): void {\n if (records.length === 0 && !lastMessageId) return;\n\n const sessionManager = openManagedSession(sessionFile, sessionDir, cwd);\n appendLogRecordsToSession(sessionManager, records);\n sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {\n source: \"log.jsonl\",\n messageCount: records.length,\n lastMessageId,\n });\n forceRewriteSession(sessionManager, sessionFile);\n}\n\ninterface HistoryWindow {\n recentDays: number;\n maxMessages: number;\n now: Date;\n}\n\nfunction syncSessionFromLog(\n sessionFile: string,\n sessionDir: string,\n cwd: string,\n records: LogRecord[],\n historyWindow: HistoryWindow,\n): void {\n if (records.length === 0) return;\n syncSessionManagerFromLog(\n openManagedSession(sessionFile, sessionDir, cwd),\n records,\n historyWindow,\n );\n}\n\nfunction syncSessionManagerFromLog(\n sessionManager: SessionManager,\n records: LogRecord[],\n historyWindow: HistoryWindow,\n): void {\n if (records.length === 0) return;\n\n const existingEntries = sessionManager.getEntries();\n const lastSyncedMessageId = getLatestChatSyncMessageId(existingEntries);\n const lastSyncedIndex = lastSyncedMessageId\n ? records.findIndex((record) => record.message.ts === lastSyncedMessageId)\n : -1;\n if (lastSyncedMessageId && lastSyncedIndex === -1) return;\n\n const syncCandidates = selectRecentMessages(records.slice(lastSyncedIndex + 1), historyWindow);\n if (syncCandidates.length === 0) return;\n\n const represented = buildRepresentedMessageCounts(existingEntries);\n const newRecords = syncCandidates.filter(\n (record) => !consumeRepresentedLogMessage(record, represented),\n );\n if (newRecords.length === 0) return;\n\n appendLogRecordsToSession(sessionManager, newRecords);\n sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {\n source: \"log.jsonl\",\n messageCount: newRecords.length,\n lastMessageId: syncCandidates.at(-1)?.message.ts,\n });\n}\n\nfunction appendLogRecordsToSession(sessionManager: SessionManager, records: LogRecord[]): void {\n for (const record of records) {\n const message = buildHistorySessionMessage(record.message);\n if (message) sessionManager.appendMessage(message);\n }\n}\n\nfunction forceRewriteSession(sessionManager: SessionManager, sessionFile: string): void {\n const header = sessionManager.getHeader();\n if (!header) return;\n\n const content = [header, ...sessionManager.getEntries()]\n .map((entry) => JSON.stringify(entry))\n .join(\"\\n\");\n atomicWritePrivateFile(sessionFile, `${content}\\n`);\n}\n\nfunction getLatestChatSyncMessageId(entries: SessionEntry[]): string | undefined {\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i];\n if (entry.type !== \"custom\" || entry.customType !== CHAT_SYNC_CUSTOM_TYPE) continue;\n if (!isRecord(entry.data)) return undefined;\n return typeof entry.data.lastMessageId === \"string\" ? entry.data.lastMessageId : undefined;\n }\n return undefined;\n}\n\nfunction buildRepresentedMessageCounts(entries: SessionEntry[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const entry of entries) {\n const comparable = comparableSessionMessage(entry);\n if (!comparable) continue;\n counts.set(comparable, (counts.get(comparable) ?? 0) + 1);\n }\n return counts;\n}\n\nfunction consumeRepresentedLogMessage(record: LogRecord, counts: Map<string, number>): boolean {\n const comparable = comparableLogMessage(record.message);\n if (!comparable) return false;\n\n const count = counts.get(comparable) ?? 0;\n if (count <= 0) return false;\n counts.set(comparable, count - 1);\n return true;\n}\n\nfunction comparableSessionMessage(entry: SessionEntry): string | null {\n if (entry.type !== \"message\") return null;\n const role = entry.message.role;\n if (role !== \"user\" && role !== \"assistant\") return null;\n\n const text = normalizeComparableText(getSessionMessageText(entry));\n if (!text) return null;\n return `${role}:${text}`;\n}\n\nfunction comparableLogMessage(message: ConversationLogMessage): string | null {\n const text = message.text?.trim();\n if (!text) return null;\n return `${message.isMessagingBot ? \"assistant\" : \"user\"}:${normalizeComparableText(text)}`;\n}\n\nfunction getSessionMessageText(entry: SessionEntry): string {\n if (entry.type !== \"message\" || !(\"content\" in entry.message)) return \"\";\n const content = entry.message.content;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((part) => (part.type === \"text\" && \"text\" in part ? part.text : \"\"))\n .join(\"\\n\");\n}\n\nfunction normalizeComparableText(text: string): string {\n return text\n .replace(\n /^\\[[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}\\]\\s+\\[[^\\]]+\\](?:\\s+\\[in-thread:[^\\]]+\\])?:\\s*/,\n \"\",\n )\n .trim();\n}\n\nfunction buildHistorySessionMessage(message: ConversationLogMessage): SessionAppendMessage | null {\n const text = message.text?.trim();\n if (!text) return null;\n\n const timestamp = parseMessageTimestamp(message);\n if (!message.isMessagingBot) {\n return {\n role: \"user\",\n content: [{ type: \"text\", text: formatHistoryMessage(message) }],\n ...(timestamp !== undefined ? { timestamp } : {}),\n } as SessionAppendMessage;\n }\n\n return {\n role: \"assistant\",\n content: [{ type: \"text\", text }],\n api: \"platform-history\",\n provider: \"platform-history\",\n model: \"platform-history\",\n usage: zeroUsage(),\n stopReason: \"stop\",\n ...(timestamp !== undefined ? { timestamp } : {}),\n } as SessionAppendMessage;\n}\n\nfunction buildThreadRootSeed(\n message: ConversationLogMessage | undefined,\n): ThreadRootMessage | null {\n if (!message) return null;\n return {\n text: message.text,\n userName: message.userName,\n user: message.user,\n loggedAt: message.date ? new Date(message.date).getTime() : undefined,\n isMessagingBot: message.isMessagingBot,\n };\n}\n\nfunction parseMessageTimestamp(message: ConversationLogMessage): number | undefined {\n if (message.date) {\n const dateMs = new Date(message.date).getTime();\n if (Number.isFinite(dateMs)) return dateMs;\n }\n\n if (message.ts) {\n const tsMs = Number(message.ts) * 1000;\n if (Number.isFinite(tsMs)) return tsMs;\n }\n\n return undefined;\n}\n\nfunction formatHistoryMessage(message: ConversationLogMessage): string {\n const text = message.text?.trim() ?? \"\";\n const userLabel = message.userName || message.user || \"unknown\";\n const timestamp = message.date ? formatLocalTimestamp(new Date(message.date)) : null;\n return timestamp ? `[${timestamp}] [${userLabel}]: ${text}` : `[${userLabel}]: ${text}`;\n}\n\nfunction zeroUsage(): object {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n}\n"]}
1
+ {"version":3,"file":"agent-memory-file-manager.js","sourceRoot":"","sources":["../../src/sessions/agent-memory-file-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EACL,wBAAwB,EACxB,8BAA8B,EAC9B,oBAAoB,EACpB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,EACxB,uBAAuB,GAGxB,MAAM,YAAY,CAAC;AAEpB,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,qBAAqB,GAAG,iBAAiB,CAAC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,CAAC,IAAI,CAAC,CAAC,CAAC,oBAAoB,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACrF,OAAO,SAAS,CAAC,CAAC,CAAC,IAAI,SAAS,MAAM,SAAS,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,SAAS,MAAM,IAAI,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,SAAS;IAChB,OAAO;QACL,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,CAAC;QACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;KACrE,CAAC;AACJ,CAAC","sourcesContent":["import type { SessionEntry, SessionStore } from \"../harness/index.js\";\nimport { join } from \"path\";\nimport type { ConversationLogMessage } from \"../types.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { formatLocalTimestamp } from \"../utils/date.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport * as log from \"../log.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nimport {\n createManagedSessionFile,\n createManagedSessionFileAtPath,\n extractSessionSuffix,\n getChannelSessionDir,\n getThreadSessionFile,\n openManagedSession,\n resolveChannelSessionFile,\n tryResolveCurrentSession,\n tryResolveThreadSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./store.js\";\n\nconst DEFAULT_RECENT_DAYS = 14;\nconst DEFAULT_MAX_TOP_LEVEL_MESSAGES = 200;\nconst CHAT_SYNC_CUSTOM_TYPE = \"mikan.chat_sync\";\nconst BIWEEKLY_ROTATION_ANCHOR = new Date(2026, 0, 4); // Sunday\nconst BIWEEKLY_MS = 14 * 24 * 60 * 60 * 1000;\n\ntype SessionAppendMessage = Parameters<SessionStore[\"appendMessage\"]>[0];\n\ninterface LogRecord {\n message: ConversationLogMessage;\n index: number;\n}\n\nexport type {\n AgentMemoryFileManagerOptions,\n HasMaterializedSessionOptions,\n RegisterThreadSessionOptions,\n ResetChatSessionOptions,\n ResolveChatSessionScopeOptions,\n SyncAgentMemoryFileManagerOptions,\n ThreadBootstrapWaitOptions,\n} from \"./types.js\";\nimport type {\n AgentMemoryFileManagerOptions,\n HasMaterializedSessionOptions,\n RegisterThreadSessionOptions,\n ResetChatSessionOptions,\n ResolveChatSessionScopeOptions,\n SyncAgentMemoryFileManagerOptions,\n ThreadBootstrapWaitOptions,\n} from \"./types.js\";\n\nexport function hasMaterializedChatSession(options: HasMaterializedSessionOptions): boolean {\n if (!options.sessionKey.includes(\":\")) {\n return resolveChannelSessionFile(options.conversationDir) !== null;\n }\n return (\n tryResolveThreadSession(getThreadSessionFile(options.conversationDir, options.sessionKey)) !==\n null\n );\n}\n\nexport function registerThreadSession(options: RegisterThreadSessionOptions): string | null {\n if (!options.sessionKey.includes(\":\")) return null;\n\n const threadFile = getThreadSessionFile(options.conversationDir, options.sessionKey);\n return (\n tryResolveThreadSession(threadFile) ??\n createManagedSessionFileAtPath(threadFile, options.cwd ?? options.conversationDir)\n );\n}\n\nexport async function waitForThreadSessionBootstrap(\n options: ThreadBootstrapWaitOptions,\n): Promise<boolean> {\n const {\n parentSessionKey,\n sessionKey,\n hasThreadSession,\n isParentRunning,\n sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n pollMs = 100,\n } = options;\n\n if (!sessionKey.includes(\":\")) return false;\n if (sessionKey === parentSessionKey) return false;\n if (hasThreadSession()) return false;\n\n let waited = false;\n while (isParentRunning() && !hasThreadSession()) {\n waited = true;\n await sleep(pollMs);\n }\n\n return waited;\n}\n\nexport class AgentMemoryFileManager {\n private readonly recentDays: number;\n private readonly maxTopLevelMessages: number;\n private readonly now: () => Date;\n\n constructor(options: AgentMemoryFileManagerOptions = {}) {\n this.recentDays = options.recentDays ?? DEFAULT_RECENT_DAYS;\n this.maxTopLevelMessages = options.maxTopLevelMessages ?? DEFAULT_MAX_TOP_LEVEL_MESSAGES;\n this.now = options.now ?? (() => new Date());\n }\n\n async resolveSessionScope(\n options: ResolveChatSessionScopeOptions,\n ): Promise<ResolvedSessionScope> {\n const cwd = options.cwd ?? options.conversationDir;\n const sessionDir = getChannelSessionDir(options.conversationDir);\n\n if (!options.sessionKey.includes(\":\")) {\n const contextFile = this.resolveTopLevelSessionFile({\n conversationDir: options.conversationDir,\n sessionDir,\n cwd,\n currentMessageId: options.currentMessageId,\n rotateTopLevelSession: options.rotateTopLevelSession === true,\n });\n return { sessionDir, contextFile, threadRootMessage: null };\n }\n\n return this.resolveThreadSessionScope({\n conversationDir: options.conversationDir,\n sessionDir,\n sessionKey: options.sessionKey,\n cwd,\n currentMessageId: options.currentMessageId,\n });\n }\n\n syncSessionManager(options: SyncAgentMemoryFileManagerOptions): void {\n const records = readConversationLog(options.conversationDir);\n syncSessionManagerFromLog(\n options.sessionManager,\n selectExistingSessionSyncMessages(records, {\n sessionKey: options.sessionKey.includes(\":\") ? options.sessionKey : null,\n excludeMessageId: options.currentMessageId,\n }),\n this.historyWindow(),\n );\n }\n\n resetSession(options: ResetChatSessionOptions): string {\n const cwd = options.cwd ?? options.conversationDir;\n if (options.sessionKey.includes(\":\")) {\n return createManagedSessionFileAtPath(\n getThreadSessionFile(options.conversationDir, options.sessionKey),\n cwd,\n );\n }\n\n return createManagedSessionFile(getChannelSessionDir(options.conversationDir), cwd);\n }\n\n private resolveTopLevelSessionFile(options: {\n conversationDir: string;\n sessionDir: string;\n cwd: string;\n currentMessageId?: string;\n rotateTopLevelSession: boolean;\n }): string {\n const records = readConversationLog(options.conversationDir);\n const existing = tryResolveCurrentSession(options.sessionDir);\n if (existing && !isPlatformHistorySession(existing)) {\n if (!options.rotateTopLevelSession || !shouldRotateTopLevelSession(existing, this.now())) {\n syncSessionFromLog(\n existing,\n options.cwd,\n selectExistingSessionSyncMessages(records, {\n sessionKey: null,\n excludeMessageId: options.currentMessageId,\n }),\n this.historyWindow(),\n );\n return existing;\n }\n }\n\n const sessionFile = createManagedSessionFile(options.sessionDir, options.cwd);\n const bootstrapRecords = selectRecentTopLevelMessages(records, {\n recentDays: this.recentDays,\n maxMessages: this.maxTopLevelMessages,\n now: this.now(),\n excludeMessageId: options.currentMessageId,\n });\n bootstrapSessionFromLog(\n sessionFile,\n options.cwd,\n bootstrapRecords,\n latestSyncMessageId(records, {\n sessionKey: null,\n excludeMessageId: options.currentMessageId,\n }),\n );\n return sessionFile;\n }\n\n private historyWindow(): HistoryWindow {\n return { recentDays: this.recentDays, maxMessages: this.maxTopLevelMessages, now: this.now() };\n }\n\n private resolveThreadSessionScope(options: {\n conversationDir: string;\n sessionDir: string;\n sessionKey: string;\n cwd: string;\n currentMessageId?: string;\n }): ResolvedSessionScope {\n const threadFile = getThreadSessionFile(options.conversationDir, options.sessionKey);\n const threadId = extractSessionSuffix(options.sessionKey);\n const records = readConversationLog(options.conversationDir);\n const threadRootMessage = buildThreadRootSeed(findLogRecordById(records, threadId)?.message);\n const existing = tryResolveThreadSession(threadFile);\n if (existing) {\n syncSessionFromLog(\n existing,\n options.cwd,\n selectExistingSessionSyncMessages(records, {\n sessionKey: options.sessionKey,\n excludeMessageId: options.currentMessageId,\n }),\n this.historyWindow(),\n );\n return { sessionDir: options.sessionDir, contextFile: existing, threadRootMessage };\n }\n\n createManagedSessionFileAtPath(threadFile, options.cwd);\n const bootstrapRecords = selectThreadBootstrapMessages(records, threadId, {\n recentDays: this.recentDays,\n maxTopLevelMessages: this.maxTopLevelMessages,\n now: this.now(),\n excludeMessageId: options.currentMessageId,\n });\n bootstrapSessionFromLog(\n threadFile,\n options.cwd,\n bootstrapRecords,\n latestSyncMessageId(records, {\n sessionKey: options.sessionKey,\n excludeMessageId: options.currentMessageId,\n }),\n );\n\n return { sessionDir: options.sessionDir, contextFile: threadFile, threadRootMessage };\n }\n}\n\nfunction shouldRotateTopLevelSession(sessionFile: string, now: Date): boolean {\n const timestamp = readSessionTimestamp(sessionFile);\n return timestamp !== null && biweeklyBucket(timestamp) !== biweeklyBucket(now);\n}\n\nfunction readSessionTimestamp(sessionFile: string): Date | null {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return null;\n const firstLine = raw.split(\"\\n\").find((line) => line.trim());\n if (!firstLine) return null;\n try {\n const header = parseJsonValue(\n firstLine,\n (value): value is { timestamp?: unknown } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n if (typeof header.timestamp !== \"string\") return null;\n const date = new Date(header.timestamp);\n return Number.isFinite(date.getTime()) ? date : null;\n } catch {\n return null;\n }\n}\n\nfunction biweeklyBucket(date: Date): number {\n const weekStart = sundayStart(date).getTime();\n const anchor = sundayStart(BIWEEKLY_ROTATION_ANCHOR).getTime();\n return Math.floor((weekStart - anchor) / BIWEEKLY_MS);\n}\n\nfunction sundayStart(date: Date): Date {\n return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());\n}\n\nfunction readConversationLog(conversationDir: string): LogRecord[] {\n const logFile = join(conversationDir, \"log.jsonl\");\n const raw = readTextFileIfExists(logFile);\n if (raw === undefined) return [];\n\n const lines = raw.trim().split(\"\\n\").filter(Boolean);\n const records: LogRecord[] = [];\n for (let i = 0; i < lines.length; i++) {\n try {\n const message = parseJsonValue(\n lines[i],\n (value): value is ConversationLogMessage => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n records.push({ message, index: i });\n } catch (err) {\n log.logWarning(\n `Skipping malformed log entry at ${logFile}:${i + 1}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n return coalesceMessagingBotLogChunks(records);\n}\n\nfunction coalesceMessagingBotLogChunks(records: LogRecord[]): LogRecord[] {\n const coalesced: LogRecord[] = [];\n for (const record of records) {\n const previous = coalesced.at(-1);\n if (previous && canCoalesceMessagingBotLogChunk(previous.message, record.message)) {\n previous.message.text = `${previous.message.text ?? \"\"}${record.message.text ?? \"\"}`;\n continue;\n }\n coalesced.push({ ...record, message: { ...record.message } });\n }\n return coalesced;\n}\n\nfunction canCoalesceMessagingBotLogChunk(\n previous: ConversationLogMessage,\n current: ConversationLogMessage,\n): boolean {\n return (\n previous.isMessagingBot === true &&\n current.isMessagingBot === true &&\n !!previous.ts &&\n previous.ts === current.ts &&\n previous.threadTs === current.threadTs &&\n previous.user === current.user\n );\n}\n\nfunction findLogRecordById(records: LogRecord[], messageId: string): LogRecord | undefined {\n for (let i = records.length - 1; i >= 0; i--) {\n if (records[i].message.ts === messageId) return records[i];\n }\n return undefined;\n}\n\nfunction selectRecentTopLevelMessages(\n records: LogRecord[],\n options: {\n recentDays: number;\n maxMessages: number;\n now: Date;\n excludeMessageId?: string;\n },\n): LogRecord[] {\n return selectRecentMessages(\n records.filter((record) => isTopLevelHistoryMessage(record.message, options.excludeMessageId)),\n options,\n );\n}\n\nfunction selectRecentMessages(records: LogRecord[], options: HistoryWindow): LogRecord[] {\n const sinceMs = options.now.getTime() - options.recentDays * 24 * 60 * 60 * 1000;\n return records\n .filter((record) => isRecentHistoryMessage(record.message, sinceMs))\n .slice(-options.maxMessages);\n}\n\nfunction selectThreadBootstrapMessages(\n records: LogRecord[],\n threadId: string,\n options: {\n recentDays: number;\n maxTopLevelMessages: number;\n now: Date;\n excludeMessageId?: string;\n },\n): LogRecord[] {\n const rootRecord = findLogRecordById(records, threadId);\n const topLevelSource = rootRecord\n ? records.filter((record) => record.index <= rootRecord.index)\n : records;\n const topLevelRecords = selectRecentTopLevelMessages(topLevelSource, {\n recentDays: options.recentDays,\n maxMessages: options.maxTopLevelMessages,\n now: options.now,\n excludeMessageId: options.excludeMessageId,\n });\n const threadRecords = records.filter(\n (record) =>\n isRenderableConversationMessage(record.message, options.excludeMessageId) &&\n (record.message.ts === threadId || record.message.threadTs === threadId),\n );\n\n return dedupeAndSortRecords([...topLevelRecords, ...threadRecords]);\n}\n\nfunction isTopLevelHistoryMessage(\n message: ConversationLogMessage,\n excludeMessageId?: string,\n): boolean {\n if (!isRenderableConversationMessage(message, excludeMessageId)) return false;\n return !message.threadTs;\n}\n\nfunction isRecentHistoryMessage(message: ConversationLogMessage, sinceMs: number): boolean {\n if (!message.date) return true;\n const dateMs = new Date(message.date).getTime();\n return !Number.isFinite(dateMs) || dateMs >= sinceMs;\n}\n\nfunction selectExistingSessionSyncMessages(\n records: LogRecord[],\n options: { sessionKey: string | null; excludeMessageId?: string },\n): LogRecord[] {\n const threadId = options.sessionKey ? extractSessionSuffix(options.sessionKey) : null;\n return dedupeAndSortRecords(\n records.filter((record) => {\n if (!isRenderableConversationMessage(record.message, options.excludeMessageId)) return false;\n if (!threadId) return !record.message.threadTs;\n return record.message.ts === threadId || record.message.threadTs === threadId;\n }),\n );\n}\n\nfunction latestSyncMessageId(\n records: LogRecord[],\n options: { sessionKey: string | null; excludeMessageId?: string },\n): string | undefined {\n return selectExistingSessionSyncMessages(records, options).at(-1)?.message.ts;\n}\n\nfunction isRenderableConversationMessage(\n message: ConversationLogMessage,\n excludeMessageId?: string,\n): boolean {\n if (excludeMessageId && message.ts === excludeMessageId) return false;\n if (isChatCommandMessage(message)) return false;\n return !!message.text?.trim();\n}\n\nfunction isChatCommandMessage(message: ConversationLogMessage): boolean {\n const text = message.text?.trim() ?? \"\";\n return (\n !message.isMessagingBot &&\n /^\\/(?:pi-[\\w-]+|login|session|new|stop|model|sandbox|admin|auto-reply)(?:@\\w+)?(?:\\s|$)/i.test(\n text,\n )\n );\n}\n\nfunction dedupeAndSortRecords(records: LogRecord[]): LogRecord[] {\n const byKey = new Map<string, LogRecord>();\n for (const record of records) {\n byKey.set(record.message.ts ?? `line:${record.index}`, record);\n }\n\n return Array.from(byKey.values()).toSorted((a, b) => {\n const aTime = sortTime(a);\n const bTime = sortTime(b);\n if (aTime !== bTime) return aTime - bTime;\n return a.index - b.index;\n });\n}\n\nfunction sortTime(record: LogRecord): number {\n if (record.message.date) {\n const dateMs = new Date(record.message.date).getTime();\n if (Number.isFinite(dateMs)) return dateMs;\n }\n\n if (record.message.ts) {\n const tsMs = Number(record.message.ts) * 1000;\n if (Number.isFinite(tsMs)) return tsMs;\n }\n\n return record.index;\n}\n\nfunction bootstrapSessionFromLog(\n sessionFile: string,\n cwd: string,\n records: LogRecord[],\n lastMessageId = records.at(-1)?.message.ts,\n): void {\n if (records.length === 0 && !lastMessageId) return;\n\n const sessionManager = openManagedSession(sessionFile, cwd);\n appendLogRecordsToSession(sessionManager, records);\n sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {\n source: \"log.jsonl\",\n messageCount: records.length,\n lastMessageId,\n });\n forceRewriteSession(sessionManager, sessionFile);\n}\n\ninterface HistoryWindow {\n recentDays: number;\n maxMessages: number;\n now: Date;\n}\n\nfunction syncSessionFromLog(\n sessionFile: string,\n cwd: string,\n records: LogRecord[],\n historyWindow: HistoryWindow,\n): void {\n if (records.length === 0) return;\n syncSessionManagerFromLog(openManagedSession(sessionFile, cwd), records, historyWindow);\n}\n\nfunction syncSessionManagerFromLog(\n sessionManager: SessionStore,\n records: LogRecord[],\n historyWindow: HistoryWindow,\n): void {\n if (records.length === 0) return;\n\n const existingEntries = sessionManager.getEntries();\n const lastSyncedMessageId = getLatestChatSyncMessageId(existingEntries);\n const lastSyncedIndex = lastSyncedMessageId\n ? records.findIndex((record) => record.message.ts === lastSyncedMessageId)\n : -1;\n if (lastSyncedMessageId && lastSyncedIndex === -1) return;\n\n const syncCandidates = selectRecentMessages(records.slice(lastSyncedIndex + 1), historyWindow);\n if (syncCandidates.length === 0) return;\n\n const represented = buildRepresentedMessageCounts(existingEntries);\n const newRecords = syncCandidates.filter(\n (record) => !consumeRepresentedLogMessage(record, represented),\n );\n if (newRecords.length === 0) return;\n\n appendLogRecordsToSession(sessionManager, newRecords);\n sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {\n source: \"log.jsonl\",\n messageCount: newRecords.length,\n lastMessageId: syncCandidates.at(-1)?.message.ts,\n });\n}\n\nfunction appendLogRecordsToSession(sessionManager: SessionStore, records: LogRecord[]): void {\n for (const record of records) {\n const message = buildHistorySessionMessage(record.message);\n if (message) sessionManager.appendMessage(message);\n }\n}\n\nfunction forceRewriteSession(sessionManager: SessionStore, sessionFile: string): void {\n const header = sessionManager.getHeader();\n if (!header) return;\n\n const content = [header, ...sessionManager.getEntries()]\n .map((entry) => JSON.stringify(entry))\n .join(\"\\n\");\n atomicWritePrivateFile(sessionFile, `${content}\\n`);\n}\n\nfunction getLatestChatSyncMessageId(entries: SessionEntry[]): string | undefined {\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i];\n if (entry.type !== \"custom\" || entry.customType !== CHAT_SYNC_CUSTOM_TYPE) continue;\n if (!isRecord(entry.data)) return undefined;\n return typeof entry.data.lastMessageId === \"string\" ? entry.data.lastMessageId : undefined;\n }\n return undefined;\n}\n\nfunction buildRepresentedMessageCounts(entries: SessionEntry[]): Map<string, number> {\n const counts = new Map<string, number>();\n for (const entry of entries) {\n const comparable = comparableSessionMessage(entry);\n if (!comparable) continue;\n counts.set(comparable, (counts.get(comparable) ?? 0) + 1);\n }\n return counts;\n}\n\nfunction consumeRepresentedLogMessage(record: LogRecord, counts: Map<string, number>): boolean {\n const comparable = comparableLogMessage(record.message);\n if (!comparable) return false;\n\n const count = counts.get(comparable) ?? 0;\n if (count <= 0) return false;\n counts.set(comparable, count - 1);\n return true;\n}\n\nfunction comparableSessionMessage(entry: SessionEntry): string | null {\n if (entry.type !== \"message\") return null;\n const role = entry.message.role;\n if (role !== \"user\" && role !== \"assistant\") return null;\n\n const text = normalizeComparableText(getSessionMessageText(entry));\n if (!text) return null;\n return `${role}:${text}`;\n}\n\nfunction comparableLogMessage(message: ConversationLogMessage): string | null {\n const text = message.text?.trim();\n if (!text) return null;\n return `${message.isMessagingBot ? \"assistant\" : \"user\"}:${normalizeComparableText(text)}`;\n}\n\nfunction getSessionMessageText(entry: SessionEntry): string {\n if (entry.type !== \"message\" || !(\"content\" in entry.message)) return \"\";\n const content = entry.message.content;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((part) => (part.type === \"text\" && \"text\" in part ? part.text : \"\"))\n .join(\"\\n\");\n}\n\nfunction normalizeComparableText(text: string): string {\n return text\n .replace(\n /^\\[[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}\\]\\s+\\[[^\\]]+\\](?:\\s+\\[in-thread:[^\\]]+\\])?:\\s*/,\n \"\",\n )\n .trim();\n}\n\nfunction buildHistorySessionMessage(message: ConversationLogMessage): SessionAppendMessage | null {\n const text = message.text?.trim();\n if (!text) return null;\n\n const timestamp = parseMessageTimestamp(message);\n if (!message.isMessagingBot) {\n return {\n role: \"user\",\n content: [{ type: \"text\", text: formatHistoryMessage(message) }],\n ...(timestamp !== undefined ? { timestamp } : {}),\n } as SessionAppendMessage;\n }\n\n return {\n role: \"assistant\",\n content: [{ type: \"text\", text }],\n api: \"platform-history\",\n provider: \"platform-history\",\n model: \"platform-history\",\n usage: zeroUsage(),\n stopReason: \"stop\",\n ...(timestamp !== undefined ? { timestamp } : {}),\n } as SessionAppendMessage;\n}\n\nfunction buildThreadRootSeed(\n message: ConversationLogMessage | undefined,\n): ThreadRootMessage | null {\n if (!message) return null;\n return {\n text: message.text,\n userName: message.userName,\n user: message.user,\n loggedAt: message.date ? new Date(message.date).getTime() : undefined,\n isMessagingBot: message.isMessagingBot,\n };\n}\n\nfunction parseMessageTimestamp(message: ConversationLogMessage): number | undefined {\n if (message.date) {\n const dateMs = new Date(message.date).getTime();\n if (Number.isFinite(dateMs)) return dateMs;\n }\n\n if (message.ts) {\n const tsMs = Number(message.ts) * 1000;\n if (Number.isFinite(tsMs)) return tsMs;\n }\n\n return undefined;\n}\n\nfunction formatHistoryMessage(message: ConversationLogMessage): string {\n const text = message.text?.trim() ?? \"\";\n const userLabel = message.userName || message.user || \"unknown\";\n const timestamp = message.date ? formatLocalTimestamp(new Date(message.date)) : null;\n return timestamp ? `[${timestamp}] [${userLabel}]: ${text}` : `[${userLabel}]: ${text}`;\n}\n\nfunction zeroUsage(): object {\n return {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n totalTokens: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { SessionManager } from "@earendil-works/pi-coding-agent";
1
+ import { SessionStore } from "../harness/index.js";
2
2
  export function isPlatformHistorySession(sessionFile) {
3
3
  try {
4
- const header = SessionManager.open(sessionFile).getHeader();
4
+ const header = SessionStore.open(sessionFile).getHeader();
5
5
  return header?.source?.kind === "platform-history";
6
6
  }
7
7
  catch {
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../src/sessions/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAIjE,MAAM,UAAU,wBAAwB,CAAC,WAAmB;IAC1D,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,SAAS,EAA+B,CAAC;QACzF,OAAO,MAAM,EAAE,MAAM,EAAE,IAAI,KAAK,kBAAkB,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import { SessionManager } from \"@earendil-works/pi-coding-agent\";\nexport type { MikanSessionHeader } from \"./types.js\";\nimport type { MikanSessionHeader } from \"./types.js\";\n\nexport function isPlatformHistorySession(sessionFile: string): boolean {\n try {\n const header = SessionManager.open(sessionFile).getHeader() as MikanSessionHeader | null;\n return header?.source?.kind === \"platform-history\";\n } catch {\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../src/sessions/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAInD,MAAM,UAAU,wBAAwB,CAAC,WAAmB;IAC1D,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,SAAS,EAA+B,CAAC;QACvF,OAAO,MAAM,EAAE,MAAM,EAAE,IAAI,KAAK,kBAAkB,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import { SessionStore } from \"../harness/index.js\";\nexport type { MikanSessionHeader } from \"./types.js\";\nimport type { MikanSessionHeader } from \"./types.js\";\n\nexport function isPlatformHistorySession(sessionFile: string): boolean {\n try {\n const header = SessionStore.open(sessionFile).getHeader() as MikanSessionHeader | null;\n return header?.source?.kind === \"platform-history\";\n } catch {\n return false;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { SessionManager } from "@earendil-works/pi-coding-agent";
1
+ import { SessionStore } from "../harness/index.js";
2
2
  export type { ResolvedSessionScope, ThreadRootMessage } from "./types.js";
3
3
  /**
4
4
  * Returns the shared session directory for a conversation.
@@ -43,9 +43,9 @@ export declare function createNewSessionFile(sessionDir: string): string;
43
43
  export declare function createManagedSessionFile(sessionDir: string, cwd: string): string;
44
44
  /**
45
45
  * Open a session file with an explicit cwd, even if the file does not exist yet.
46
- * This avoids SessionManager.open() falling back to process.cwd() for fresh sessions.
46
+ * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.
47
47
  */
48
- export declare function openManagedSession(sessionFile: string, sessionDir: string, cwd: string): SessionManager;
48
+ export declare function openManagedSession(sessionFile: string, cwd: string): SessionStore;
49
49
  /**
50
50
  * Creates or overwrites a fixed-path session file with a valid session header.
51
51
  */
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","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DD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI1E;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE1E;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3E"}
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "crypto";
2
2
  import { existsSync, mkdirSync, rmSync } from "fs";
3
3
  import { basename, dirname, join } from "path";
4
- import { SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import { SessionStore } from "../harness/index.js";
5
5
  import { isRecord, parseJsonValue, readTextFileIfExists } from "../utils/file-guards.js";
6
6
  import { atomicWritePrivateFile } from "../utils/fs-atomic.js";
7
7
  import { isPlatformHistorySession } from "./metadata.js";
@@ -79,13 +79,13 @@ export function createManagedSessionFile(sessionDir, cwd) {
79
79
  }
80
80
  /**
81
81
  * Open a session file with an explicit cwd, even if the file does not exist yet.
82
- * This avoids SessionManager.open() falling back to process.cwd() for fresh sessions.
82
+ * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.
83
83
  */
84
- export function openManagedSession(sessionFile, sessionDir, cwd) {
84
+ export function openManagedSession(sessionFile, cwd) {
85
85
  if (shouldRecreatePreinitializedSession(sessionFile)) {
86
86
  rmSync(sessionFile, { force: true });
87
87
  }
88
- return SessionManager.open(sessionFile, sessionDir, cwd);
88
+ return SessionStore.open(sessionFile, cwd);
89
89
  }
90
90
  function createSessionFilename(sessionId = randomUUID()) {
91
91
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM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C;AACpE,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { existsSync, mkdirSync, rmSync } from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { SessionManager } from \"@earendil-works/pi-coding-agent\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nexport type { ResolvedSessionScope, ThreadRootMessage } from \"./types.js\";\n\n/**\n * Returns the shared session directory for a conversation.\n * Channel sessions use a current pointer within this directory.\n * Thread sessions are stored as fixed files within the same directory.\n */\nexport function getChannelSessionDir(channelDir: string): string {\n return join(channelDir, \"sessions\");\n}\n\n/**\n * Resolves the current active session file for a session directory.\n * Reads the \"current\" pointer file; creates a new session if none exists\n * or the pointed-to file is missing.\n */\nexport function resolveSessionFile(sessionDir: string): string {\n const existing = tryResolveCurrentSession(sessionDir);\n if (existing) return existing;\n return createNewSessionFile(sessionDir);\n}\n\n/**\n * Resolve the current active session file for a session directory.\n * Creates a fully initialized persistent session with the provided cwd when none exists.\n */\nexport function resolveManagedSessionFile(sessionDir: string, cwd: string): string {\n const existingPath = getCurrentSessionPath(sessionDir);\n if (existingPath && !isPlatformHistorySession(existingPath)) return existingPath;\n return createManagedSessionFile(sessionDir, cwd);\n}\n\n/**\n * Extracts the short UUID from a session file path.\n * e.g. \"2026-04-05T00-00_7b54cf90.jsonl\" → \"7b54cf90\"\n */\nexport function extractSessionUuid(sessionFile: string): string {\n return basename(sessionFile).replace(\".jsonl\", \"\").split(\"_\").pop()!;\n}\n\n/**\n * Extracts the thread/suffix part of a session key.\n * \"channelId:threadId\" → \"threadId\", \"channelId\" → \"channelId\"\n */\nexport function extractSessionSuffix(sessionKey: string): string {\n const parts = sessionKey.split(\":\");\n return parts.length > 1 ? parts[parts.length - 1] : sessionKey;\n}\n\n/**\n * Creates an empty timestamped file and updates the \"current\" pointer.\n * Used only by tests for placeholder-file scenarios.\n *\n * Order matters: write the session file first, then atomic-rename the pointer\n * last so a crash mid-create never leaves \"current\" pointing at a missing file.\n */\nexport function createNewSessionFile(sessionDir: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const filename = createSessionFilename();\n const filePath = join(sessionDir, filename);\n atomicWritePrivateFile(filePath, \"\");\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n return filePath;\n}\n\n/**\n * Creates a new persistent session file with a proper SessionManager header and cwd.\n * Also updates the \"current\" pointer. Header is written before the pointer flips so a\n * partial create cannot leave \"current\" pointing at a missing file.\n */\nexport function createManagedSessionFile(sessionDir: string, cwd: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const sessionId = randomUUID();\n const sessionFile = join(sessionDir, createSessionFilename(sessionId));\n writeSessionHeader(sessionFile, cwd, sessionId);\n setCurrentPointer(sessionDir, sessionFile);\n return sessionFile;\n}\n\n/**\n * Open a session file with an explicit cwd, even if the file does not exist yet.\n * This avoids SessionManager.open() falling back to process.cwd() for fresh sessions.\n */\nexport function openManagedSession(\n sessionFile: string,\n sessionDir: string,\n cwd: string,\n): SessionManager {\n if (shouldRecreatePreinitializedSession(sessionFile)) {\n rmSync(sessionFile, { force: true });\n }\n\n return SessionManager.open(sessionFile, sessionDir, cwd);\n}\n\nfunction createSessionFilename(sessionId = randomUUID()): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${timestamp}_${sessionId.slice(0, 8)}.jsonl`;\n}\n\nfunction setCurrentPointer(sessionDir: string, sessionFilePath: string): void {\n const filename = sessionFilePath.split(\"/\").pop()!;\n mkdirSync(sessionDir, { recursive: true });\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n}\n\n/**\n * Creates or overwrites a fixed-path session file with a valid session header.\n */\nexport function createManagedSessionFileAtPath(sessionFile: string, cwd: string): string {\n writeSessionHeader(sessionFile, cwd);\n return sessionFile;\n}\n\nfunction writeSessionHeader(sessionFile: string, cwd: string, sessionId = randomUUID()): void {\n const sessionDir = dirname(sessionFile);\n mkdirSync(sessionDir, { recursive: true });\n const header = {\n type: \"session\",\n version: 3,\n id: sessionId,\n timestamp: new Date().toISOString(),\n cwd,\n };\n atomicWritePrivateFile(sessionFile, `${JSON.stringify(header)}\\n`);\n}\n\n/**\n * Returns the fixed session file path for a Slack thread.\n */\nexport function getThreadSessionFile(channelDir: string, sessionKey: string): string {\n return join(getChannelSessionDir(channelDir), `${extractSessionSuffix(sessionKey)}.jsonl`);\n}\n\nfunction hasSessionHeader(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const entry = parseSessionEntry(trimmed);\n return entry.type === \"session\";\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction shouldRecreatePreinitializedSession(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const entries = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(parseSessionEntry);\n\n return entries.length === 1 && entries[0]?.type === \"session\";\n } catch {\n return false;\n }\n}\n\nfunction parseSessionEntry(line: string): { type?: string } {\n return parseJsonValue(\n line,\n (value): value is { type?: string } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n}\n\nfunction getCurrentSessionPath(sessionDir: string): string | null {\n const pointerFile = join(sessionDir, \"current\");\n const filename = readTextFileIfExists(pointerFile)?.trim();\n if (!filename) return null;\n return join(sessionDir, filename);\n}\n\n/**\n * Try to resolve an existing current session file.\n * Returns null if no current pointer exists or the pointed file has no valid session header.\n */\nexport function tryResolveCurrentSession(sessionDir: string): string | null {\n const fullPath = getCurrentSessionPath(sessionDir);\n if (fullPath && existsSync(fullPath) && hasSessionHeader(fullPath)) return fullPath;\n return null;\n}\n\n/**\n * Try to resolve an existing thread session file.\n * Returns the file path if found, or null if no valid thread session exists yet.\n */\nexport function tryResolveThreadSession(sessionFile: string): string | null {\n return existsSync(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;\n}\n\n/**\n * Resolve the channel's current session file path.\n * Returns null if no channel session exists.\n */\nexport function resolveChannelSessionFile(channelDir: string): string | null {\n return tryResolveCurrentSession(getChannelSessionDir(channelDir));\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAGzD;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAkB;IACrD,OAAO,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;AACtC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,UAAkB;IACnD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC;IACtD,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,OAAO,oBAAoB,CAAC,UAAU,CAAC,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,UAAkB,EAAE,GAAW;IACvE,MAAM,YAAY,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACvD,IAAI,YAAY,IAAI,CAAC,wBAAwB,CAAC,YAAY,CAAC;QAAE,O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AO,QAAQ,CAAC;IACpF,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CAAC,WAAmB;IACzD,OAAO,UAAU,CAAC,WAAW,CAAC,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;AACvF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,UAAkB;IAC1D,OAAO,wBAAwB,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { existsSync, mkdirSync, rmSync } from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { SessionStore } from \"../harness/index.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../utils/fs-atomic.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nexport type { ResolvedSessionScope, ThreadRootMessage } from \"./types.js\";\n\n/**\n * Returns the shared session directory for a conversation.\n * Channel sessions use a current pointer within this directory.\n * Thread sessions are stored as fixed files within the same directory.\n */\nexport function getChannelSessionDir(channelDir: string): string {\n return join(channelDir, \"sessions\");\n}\n\n/**\n * Resolves the current active session file for a session directory.\n * Reads the \"current\" pointer file; creates a new session if none exists\n * or the pointed-to file is missing.\n */\nexport function resolveSessionFile(sessionDir: string): string {\n const existing = tryResolveCurrentSession(sessionDir);\n if (existing) return existing;\n return createNewSessionFile(sessionDir);\n}\n\n/**\n * Resolve the current active session file for a session directory.\n * Creates a fully initialized persistent session with the provided cwd when none exists.\n */\nexport function resolveManagedSessionFile(sessionDir: string, cwd: string): string {\n const existingPath = getCurrentSessionPath(sessionDir);\n if (existingPath && !isPlatformHistorySession(existingPath)) return existingPath;\n return createManagedSessionFile(sessionDir, cwd);\n}\n\n/**\n * Extracts the short UUID from a session file path.\n * e.g. \"2026-04-05T00-00_7b54cf90.jsonl\" → \"7b54cf90\"\n */\nexport function extractSessionUuid(sessionFile: string): string {\n return basename(sessionFile).replace(\".jsonl\", \"\").split(\"_\").pop()!;\n}\n\n/**\n * Extracts the thread/suffix part of a session key.\n * \"channelId:threadId\" → \"threadId\", \"channelId\" → \"channelId\"\n */\nexport function extractSessionSuffix(sessionKey: string): string {\n const parts = sessionKey.split(\":\");\n return parts.length > 1 ? parts[parts.length - 1] : sessionKey;\n}\n\n/**\n * Creates an empty timestamped file and updates the \"current\" pointer.\n * Used only by tests for placeholder-file scenarios.\n *\n * Order matters: write the session file first, then atomic-rename the pointer\n * last so a crash mid-create never leaves \"current\" pointing at a missing file.\n */\nexport function createNewSessionFile(sessionDir: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const filename = createSessionFilename();\n const filePath = join(sessionDir, filename);\n atomicWritePrivateFile(filePath, \"\");\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n return filePath;\n}\n\n/**\n * Creates a new persistent session file with a proper SessionManager header and cwd.\n * Also updates the \"current\" pointer. Header is written before the pointer flips so a\n * partial create cannot leave \"current\" pointing at a missing file.\n */\nexport function createManagedSessionFile(sessionDir: string, cwd: string): string {\n mkdirSync(sessionDir, { recursive: true });\n const sessionId = randomUUID();\n const sessionFile = join(sessionDir, createSessionFilename(sessionId));\n writeSessionHeader(sessionFile, cwd, sessionId);\n setCurrentPointer(sessionDir, sessionFile);\n return sessionFile;\n}\n\n/**\n * Open a session file with an explicit cwd, even if the file does not exist yet.\n * This avoids SessionStore.open() falling back to process.cwd() for fresh sessions.\n */\nexport function openManagedSession(sessionFile: string, cwd: string): SessionStore {\n if (shouldRecreatePreinitializedSession(sessionFile)) {\n rmSync(sessionFile, { force: true });\n }\n\n return SessionStore.open(sessionFile, cwd);\n}\n\nfunction createSessionFilename(sessionId = randomUUID()): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n return `${timestamp}_${sessionId.slice(0, 8)}.jsonl`;\n}\n\nfunction setCurrentPointer(sessionDir: string, sessionFilePath: string): void {\n const filename = sessionFilePath.split(\"/\").pop()!;\n mkdirSync(sessionDir, { recursive: true });\n atomicWritePrivateFile(join(sessionDir, \"current\"), filename);\n}\n\n/**\n * Creates or overwrites a fixed-path session file with a valid session header.\n */\nexport function createManagedSessionFileAtPath(sessionFile: string, cwd: string): string {\n writeSessionHeader(sessionFile, cwd);\n return sessionFile;\n}\n\nfunction writeSessionHeader(sessionFile: string, cwd: string, sessionId = randomUUID()): void {\n const sessionDir = dirname(sessionFile);\n mkdirSync(sessionDir, { recursive: true });\n const header = {\n type: \"session\",\n version: 3,\n id: sessionId,\n timestamp: new Date().toISOString(),\n cwd,\n };\n atomicWritePrivateFile(sessionFile, `${JSON.stringify(header)}\\n`);\n}\n\n/**\n * Returns the fixed session file path for a Slack thread.\n */\nexport function getThreadSessionFile(channelDir: string, sessionKey: string): string {\n return join(getChannelSessionDir(channelDir), `${extractSessionSuffix(sessionKey)}.jsonl`);\n}\n\nfunction hasSessionHeader(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n const entry = parseSessionEntry(trimmed);\n return entry.type === \"session\";\n }\n } catch {\n return false;\n }\n return false;\n}\n\nfunction shouldRecreatePreinitializedSession(sessionFile: string): boolean {\n try {\n const raw = readTextFileIfExists(sessionFile);\n if (raw === undefined) return false;\n const entries = raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(parseSessionEntry);\n\n return entries.length === 1 && entries[0]?.type === \"session\";\n } catch {\n return false;\n }\n}\n\nfunction parseSessionEntry(line: string): { type?: string } {\n return parseJsonValue(\n line,\n (value): value is { type?: string } => isRecord(value),\n (detail) => (detail === \"unexpected JSON shape\" ? \"expected a JSON object\" : detail),\n );\n}\n\nfunction getCurrentSessionPath(sessionDir: string): string | null {\n const pointerFile = join(sessionDir, \"current\");\n const filename = readTextFileIfExists(pointerFile)?.trim();\n if (!filename) return null;\n return join(sessionDir, filename);\n}\n\n/**\n * Try to resolve an existing current session file.\n * Returns null if no current pointer exists or the pointed file has no valid session header.\n */\nexport function tryResolveCurrentSession(sessionDir: string): string | null {\n const fullPath = getCurrentSessionPath(sessionDir);\n if (fullPath && existsSync(fullPath) && hasSessionHeader(fullPath)) return fullPath;\n return null;\n}\n\n/**\n * Try to resolve an existing thread session file.\n * Returns the file path if found, or null if no valid thread session exists yet.\n */\nexport function tryResolveThreadSession(sessionFile: string): string | null {\n return existsSync(sessionFile) && hasSessionHeader(sessionFile) ? sessionFile : null;\n}\n\n/**\n * Resolve the channel's current session file path.\n * Returns null if no channel session exists.\n */\nexport function resolveChannelSessionFile(channelDir: string): string | null {\n return tryResolveCurrentSession(getChannelSessionDir(channelDir));\n}\n"]}
@@ -49,7 +49,7 @@ export interface ResolveChatSessionScopeOptions {
49
49
  export interface SyncAgentMemoryFileManagerOptions {
50
50
  conversationDir: string;
51
51
  sessionKey: string;
52
- sessionManager: import("@earendil-works/pi-coding-agent").SessionManager;
52
+ sessionManager: import("../harness/index.js").SessionStore;
53
53
  /** The triggering platform message ID. Excluded from sync to avoid duplicate user turns. */
54
54
  currentMessageId?: string;
55
55
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAItD,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE;QACP,IAAI,CAAC,EAAE,MAAM,CAAC;QAC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,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,4BAA4B;IAC3C,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,6BAA6B;IAC5C,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,0BAA0B;IACzC,gBAAgB,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,MAAM,OAAO,CAAC;IAChC,eAAe,EAAE,MAAM,OAAO,CAAC;IAC/B,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ConversationKind } from \"../adapter.js\";\n\n// ── session metadata ─────────────────────────────────────────────────────────\n\nexport interface MikanSessionHeader {\n type?: string;\n version?: number;\n id?: string;\n timestamp?: string;\n cwd?: string;\n parentSession?: string;\n source?: {\n kind?: string;\n file?: string;\n recentDays?: number;\n };\n}\n\n// ── session policy ───────────────────────────────────────────────────────────\n\nexport interface ResolveSessionKeyOptions {\n conversationId: string;\n conversationKind: ConversationKind;\n messageId: string;\n threadTs?: string;\n persistentTopLevel?: boolean;\n scopeDirectThreads?: boolean;\n}\n\n// ── session store ────────────────────────────────────────────────────────────\n\nexport interface ThreadRootMessage {\n text?: string;\n userName?: string;\n user?: string;\n loggedAt?: number;\n isMessagingBot?: boolean;\n}\n\nexport interface ResolvedSessionScope {\n sessionDir: string;\n contextFile: string;\n threadRootMessage: ThreadRootMessage | null;\n}\n\n// ── chat session manager ─────────────────────────────────────────────────────\n\nexport interface AgentMemoryFileManagerOptions {\n recentDays?: number;\n maxTopLevelMessages?: number;\n now?: () => Date;\n}\n\nexport interface ResolveChatSessionScopeOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n /** The triggering platform message ID. Excluded from bootstrap to avoid duplicate user turns. */\n currentMessageId?: string;\n /** Rotate top-level shared sessions on biweekly Sunday boundaries. */\n rotateTopLevelSession?: boolean;\n}\n\nexport interface SyncAgentMemoryFileManagerOptions {\n conversationDir: string;\n sessionKey: string;\n sessionManager: import(\"@earendil-works/pi-coding-agent\").SessionManager;\n /** The triggering platform message ID. Excluded from sync to avoid duplicate user turns. */\n currentMessageId?: string;\n}\n\nexport interface ResetChatSessionOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n}\n\nexport interface RegisterThreadSessionOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n}\n\nexport interface HasMaterializedSessionOptions {\n conversationDir: string;\n sessionKey: string;\n}\n\nexport interface ThreadBootstrapWaitOptions {\n parentSessionKey: string;\n sessionKey: string;\n hasThreadSession: () => boolean;\n isParentRunning: () => boolean;\n sleep?: (ms: number) => Promise<void>;\n pollMs?: number;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ConversationKind } from \"../adapter.js\";\n\n// ── session metadata ─────────────────────────────────────────────────────────\n\nexport interface MikanSessionHeader {\n type?: string;\n version?: number;\n id?: string;\n timestamp?: string;\n cwd?: string;\n parentSession?: string;\n source?: {\n kind?: string;\n file?: string;\n recentDays?: number;\n };\n}\n\n// ── session policy ───────────────────────────────────────────────────────────\n\nexport interface ResolveSessionKeyOptions {\n conversationId: string;\n conversationKind: ConversationKind;\n messageId: string;\n threadTs?: string;\n persistentTopLevel?: boolean;\n scopeDirectThreads?: boolean;\n}\n\n// ── session store ────────────────────────────────────────────────────────────\n\nexport interface ThreadRootMessage {\n text?: string;\n userName?: string;\n user?: string;\n loggedAt?: number;\n isMessagingBot?: boolean;\n}\n\nexport interface ResolvedSessionScope {\n sessionDir: string;\n contextFile: string;\n threadRootMessage: ThreadRootMessage | null;\n}\n\n// ── chat session manager ─────────────────────────────────────────────────────\n\nexport interface AgentMemoryFileManagerOptions {\n recentDays?: number;\n maxTopLevelMessages?: number;\n now?: () => Date;\n}\n\nexport interface ResolveChatSessionScopeOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n /** The triggering platform message ID. Excluded from bootstrap to avoid duplicate user turns. */\n currentMessageId?: string;\n /** Rotate top-level shared sessions on biweekly Sunday boundaries. */\n rotateTopLevelSession?: boolean;\n}\n\nexport interface SyncAgentMemoryFileManagerOptions {\n conversationDir: string;\n sessionKey: string;\n sessionManager: import(\"../harness/index.js\").SessionStore;\n /** The triggering platform message ID. Excluded from sync to avoid duplicate user turns. */\n currentMessageId?: string;\n}\n\nexport interface ResetChatSessionOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n}\n\nexport interface RegisterThreadSessionOptions {\n conversationDir: string;\n sessionKey: string;\n cwd?: string;\n}\n\nexport interface HasMaterializedSessionOptions {\n conversationDir: string;\n sessionKey: string;\n}\n\nexport interface ThreadBootstrapWaitOptions {\n parentSessionKey: string;\n sessionKey: string;\n hasThreadSession: () => boolean;\n isParentRunning: () => boolean;\n sleep?: (ms: number) => Promise<void>;\n pollMs?: number;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"trigger.d.ts","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAStD,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE/E;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,OAAO,CAAC,aAAa,EAAE,sBAAsB,CAAC,GACrD,aAAa,CAEf;AAED;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAAC,KAAK,EAAE;IACnD,KAAK,EAAE,iBAAiB,CAAC;IACzB,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,aAAa,CAAC,CA4BzB"}
1
+ {"version":3,"file":"trigger.d.ts","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAOtD,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE/E;;;GAGG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,OAAO,CAAC,aAAa,EAAE,sBAAsB,CAAC,GACrD,aAAa,CAEf;AAED;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAAC,KAAK,EAAE;IACnD,KAAK,EAAE,iBAAiB,CAAC;IACzB,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,aAAa,CAAC,CA4BzB"}
package/dist/trigger.js CHANGED
@@ -1,9 +1,7 @@
1
- import { completeSimple } from "@earendil-works/pi-ai/compat";
2
- import { AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
1
+ import { join } from "path";
2
+ import { MikanModels } from "./harness/index.js";
3
3
  import { loadAutoReplyJudgeModel, loadConversationAutoReplyConfig } from "./config.js";
4
4
  import * as log from "./log.js";
5
- import { homedir } from "os";
6
- import { join } from "path";
7
5
  import { resolveConfiguredModel } from "./model-registry.js";
8
6
  const JUDGE_TIMEOUT_MS = 10_000;
9
7
  /**
@@ -66,13 +64,9 @@ function withTimeout(promise, ms) {
66
64
  }
67
65
  async function judgeAutoReplyWithLlm(input) {
68
66
  const judgeConfig = loadAutoReplyJudgeModel(input.conversationDir);
69
- const modelRegistry = ModelRegistry.create(AuthStorage.create(join(homedir(), ".pi", "mikan", "auth.json")));
70
- const model = resolveConfiguredModel(modelRegistry, judgeConfig.provider, judgeConfig.model);
71
- const auth = await modelRegistry.getApiKeyAndHeaders(model);
72
- if (!auth.ok) {
73
- throw new Error(auth.error);
74
- }
75
- const answer = await completeSimple(model, {
67
+ const models = MikanModels.create();
68
+ const model = resolveConfiguredModel(models, judgeConfig.provider, judgeConfig.model);
69
+ const answer = await models.models.completeSimple(model, {
76
70
  systemPrompt: "You decide whether a bot should reply to a group/channel message. " +
77
71
  "Use only the rules provided by the user. Answer exactly YES or NO.",
78
72
  messages: [
@@ -94,8 +88,6 @@ async function judgeAutoReplyWithLlm(input) {
94
88
  temperature: 0,
95
89
  maxTokens: 4,
96
90
  reasoning: "minimal",
97
- apiKey: auth.apiKey,
98
- headers: auth.headers,
99
91
  });
100
92
  const text = answer.content
101
93
  .filter((part) => part.type === "text")
@@ -1 +1 @@
1
- {"version":3,"file":"trigger.js","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAE7E,OAAO,EAAE,uBAAuB,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAKhC;;;GAGG;AACH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CAAC,EAAE,CAAC;SACR,IAAI,EAAE;SACN,WAAW,EAAE,CAAC;IACjB,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { completeSimple } from \"@earendil-works/pi-ai/compat\";\nimport { AuthStorage, ModelRegistry } from \"@earendil-works/pi-coding-agent\";\nimport type { ConversationEvent } from \"./adapter.js\";\nimport { loadAutoReplyJudgeModel, loadConversationAutoReplyConfig } from \"./config.js\";\nimport * as log from \"./log.js\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport { resolveConfiguredModel } from \"./model-registry.js\";\n\nconst JUDGE_TIMEOUT_MS = 10_000;\n\nexport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\nimport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\n\n/**\n * Trivially decide non-auto-reply intents synchronously. For \"auto-reply-candidate\"\n * callers must use {@link evaluateAutoReplyPolicy}.\n */\nexport function decideTrigger(\n intent: Exclude<TriggerIntent, \"auto-reply-candidate\">,\n): TriggerResult {\n return { trigger: true, reason: intent };\n}\n\n/**\n * Decide whether to auto-reply. Never throws — judge errors and timeouts are\n * folded into a `trigger: false` result with a distinct reason, so adapters\n * can apply a single uniform \"do not trigger, but still log\" policy.\n *\n * @deprecated Auto-reply is kept for compatibility while its future is undecided.\n */\nexport async function evaluateAutoReplyPolicy(input: {\n event: ConversationEvent;\n workingDir: string | undefined;\n judge?: AutoReplyJudge;\n timeoutMs?: number;\n}): Promise<TriggerResult> {\n const { event, workingDir, judge = judgeAutoReplyWithLlm, timeoutMs = JUDGE_TIMEOUT_MS } = input;\n if (!workingDir) return { trigger: false, reason: \"auto-reply-unconfigured\" };\n\n const conversationDir = join(workingDir, event.conversationId);\n\n try {\n const config = loadConversationAutoReplyConfig(conversationDir);\n if (!config.enabled) return { trigger: false, reason: \"auto-reply-disabled\" };\n if (config.rules.length === 0) {\n return { trigger: true, reason: \"auto-reply-enabled\" };\n }\n\n const shouldReply = await withTimeout(\n judge({ event, rules: config.rules, conversationDir }),\n timeoutMs,\n );\n return shouldReply\n ? { trigger: true, reason: \"auto-reply-rule-match\" }\n : { trigger: false, reason: \"auto-reply-rule-no-match\" };\n } catch (err) {\n if (err instanceof JudgeTimeoutError) {\n log.logWarning(\"Auto-reply judge timed out\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-timeout\" };\n }\n log.logWarning(\"Auto-reply policy evaluation failed\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-failed\" };\n }\n}\n\nclass JudgeTimeoutError extends Error {\n constructor(ms: number) {\n super(`auto-reply judge exceeded ${ms}ms`);\n this.name = \"JudgeTimeoutError\";\n }\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new JudgeTimeoutError(ms)), ms);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\nasync function judgeAutoReplyWithLlm(input: {\n event: ConversationEvent;\n rules: string[];\n conversationDir: string;\n}): Promise<boolean> {\n const judgeConfig = loadAutoReplyJudgeModel(input.conversationDir);\n const modelRegistry = ModelRegistry.create(\n AuthStorage.create(join(homedir(), \".pi\", \"mikan\", \"auth.json\")),\n );\n const model = resolveConfiguredModel(modelRegistry, judgeConfig.provider, judgeConfig.model);\n const auth = await modelRegistry.getApiKeyAndHeaders(model);\n if (!auth.ok) {\n throw new Error(auth.error);\n }\n\n const answer = await completeSimple(\n model,\n {\n systemPrompt:\n \"You decide whether a bot should reply to a group/channel message. \" +\n \"Use only the rules provided by the user. Answer exactly YES or NO.\",\n messages: [\n {\n role: \"user\",\n timestamp: Date.now(),\n content: [\n \"Rules:\",\n ...input.rules.map((rule, index) => `${index + 1}. ${rule}`),\n \"\",\n \"Message:\",\n input.event.text,\n \"\",\n \"Should the bot reply? Answer exactly YES or NO.\",\n ].join(\"\\n\"),\n },\n ],\n },\n {\n temperature: 0,\n maxTokens: 4,\n reasoning: \"minimal\",\n apiKey: auth.apiKey,\n headers: auth.headers,\n },\n );\n const text = answer.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n .trim()\n .toUpperCase();\n return /^YES\\b/.test(text);\n}\n"]}
1
+ {"version":3,"file":"trigger.js","sourceRoot":"","sources":["../src/trigger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD,OAAO,EAAE,uBAAuB,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAKhC;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,MAAsD;IAEtD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,KAK7C;IACC,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,GAAG,qBAAqB,EAAE,SAAS,GAAG,gBAAgB,EAAE,GAAG,KAAK,CAAC;IACjG,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,yBAAyB,EAAE,CAAC;IAE9E,MAAM,eAAe,GAAG,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IAE/D,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,+BAA+B,CAAC,eAAe,CAAC,CAAC;QAChE,IAAI,CAAC,MAAM,CAAC,OAAO;YAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,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C;QACZ,SAAS,EAAE,SAAS;KACrB,CACF,CAAC;IACF,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO;SACxB,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;SACtC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;SACxB,IAAI,CAAC,EAAE,CAAC;SACR,IAAI,EAAE;SACN,WAAW,EAAE,CAAC;IACjB,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import { join } from \"path\";\nimport { MikanModels } from \"./harness/index.js\";\nimport type { ConversationEvent } from \"./adapter.js\";\nimport { loadAutoReplyJudgeModel, loadConversationAutoReplyConfig } from \"./config.js\";\nimport * as log from \"./log.js\";\nimport { resolveConfiguredModel } from \"./model-registry.js\";\n\nconst JUDGE_TIMEOUT_MS = 10_000;\n\nexport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\nimport type { AutoReplyJudge, TriggerIntent, TriggerResult } from \"./types.js\";\n\n/**\n * Trivially decide non-auto-reply intents synchronously. For \"auto-reply-candidate\"\n * callers must use {@link evaluateAutoReplyPolicy}.\n */\nexport function decideTrigger(\n intent: Exclude<TriggerIntent, \"auto-reply-candidate\">,\n): TriggerResult {\n return { trigger: true, reason: intent };\n}\n\n/**\n * Decide whether to auto-reply. Never throws — judge errors and timeouts are\n * folded into a `trigger: false` result with a distinct reason, so adapters\n * can apply a single uniform \"do not trigger, but still log\" policy.\n *\n * @deprecated Auto-reply is kept for compatibility while its future is undecided.\n */\nexport async function evaluateAutoReplyPolicy(input: {\n event: ConversationEvent;\n workingDir: string | undefined;\n judge?: AutoReplyJudge;\n timeoutMs?: number;\n}): Promise<TriggerResult> {\n const { event, workingDir, judge = judgeAutoReplyWithLlm, timeoutMs = JUDGE_TIMEOUT_MS } = input;\n if (!workingDir) return { trigger: false, reason: \"auto-reply-unconfigured\" };\n\n const conversationDir = join(workingDir, event.conversationId);\n\n try {\n const config = loadConversationAutoReplyConfig(conversationDir);\n if (!config.enabled) return { trigger: false, reason: \"auto-reply-disabled\" };\n if (config.rules.length === 0) {\n return { trigger: true, reason: \"auto-reply-enabled\" };\n }\n\n const shouldReply = await withTimeout(\n judge({ event, rules: config.rules, conversationDir }),\n timeoutMs,\n );\n return shouldReply\n ? { trigger: true, reason: \"auto-reply-rule-match\" }\n : { trigger: false, reason: \"auto-reply-rule-no-match\" };\n } catch (err) {\n if (err instanceof JudgeTimeoutError) {\n log.logWarning(\"Auto-reply judge timed out\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-timeout\" };\n }\n log.logWarning(\"Auto-reply policy evaluation failed\", String(err));\n return { trigger: false, reason: \"auto-reply-judge-failed\" };\n }\n}\n\nclass JudgeTimeoutError extends Error {\n constructor(ms: number) {\n super(`auto-reply judge exceeded ${ms}ms`);\n this.name = \"JudgeTimeoutError\";\n }\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new JudgeTimeoutError(ms)), ms);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n },\n );\n });\n}\n\nasync function judgeAutoReplyWithLlm(input: {\n event: ConversationEvent;\n rules: string[];\n conversationDir: string;\n}): Promise<boolean> {\n const judgeConfig = loadAutoReplyJudgeModel(input.conversationDir);\n const models = MikanModels.create();\n const model = resolveConfiguredModel(models, judgeConfig.provider, judgeConfig.model);\n\n const answer = await models.models.completeSimple(\n model,\n {\n systemPrompt:\n \"You decide whether a bot should reply to a group/channel message. \" +\n \"Use only the rules provided by the user. Answer exactly YES or NO.\",\n messages: [\n {\n role: \"user\",\n timestamp: Date.now(),\n content: [\n \"Rules:\",\n ...input.rules.map((rule, index) => `${index + 1}. ${rule}`),\n \"\",\n \"Message:\",\n input.event.text,\n \"\",\n \"Should the bot reply? Answer exactly YES or NO.\",\n ].join(\"\\n\"),\n },\n ],\n },\n {\n temperature: 0,\n maxTokens: 4,\n reasoning: \"minimal\",\n },\n );\n const text = answer.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\")\n .trim()\n .toUpperCase();\n return /^YES\\b/.test(text);\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -136,6 +136,12 @@ export interface MessagingBot {
136
136
  style?: "muted" | "error";
137
137
  }): Promise<void>;
138
138
  }
139
+ /**
140
+ * Post a plain message to a conversation without triggering an agent run.
141
+ * Backs extension `api.notify`; implemented in main.ts over the platform bots.
142
+ * `platform` is required only when more than one platform is running.
143
+ */
144
+ export type PlatformNotifier = (conversationId: string, text: string, platform?: string) => Promise<void>;
139
145
  /** Normalized platform data and reply hook for one event. */
140
146
  export interface ConversationContext {
141
147
  message: ConversationMessage;