@geminixiang/mikan 1.0.0-beta.20 → 1.0.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +18 -11
- package/dist/adapters/buffered-responder.d.ts +60 -0
- package/dist/adapters/buffered-responder.d.ts.map +1 -0
- package/dist/adapters/buffered-responder.js +201 -0
- package/dist/adapters/buffered-responder.js.map +1 -0
- package/dist/adapters/discord/context.d.ts.map +1 -1
- package/dist/adapters/discord/context.js +42 -177
- package/dist/adapters/discord/context.js.map +1 -1
- package/dist/adapters/github/bot.d.ts +14 -76
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +52 -443
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/client.d.ts +4 -0
- package/dist/adapters/github/client.d.ts.map +1 -1
- package/dist/adapters/github/client.js +5 -0
- package/dist/adapters/github/client.js.map +1 -1
- package/dist/adapters/github/context.d.ts.map +1 -1
- package/dist/adapters/github/context.js +32 -104
- package/dist/adapters/github/context.js.map +1 -1
- package/dist/adapters/github/github-ops.d.ts +90 -0
- package/dist/adapters/github/github-ops.d.ts.map +1 -0
- package/dist/adapters/github/github-ops.js +405 -0
- package/dist/adapters/github/github-ops.js.map +1 -0
- package/dist/adapters/github/repo.d.ts +2 -0
- package/dist/adapters/github/repo.d.ts.map +1 -1
- package/dist/adapters/github/repo.js +5 -0
- package/dist/adapters/github/repo.js.map +1 -1
- package/dist/adapters/github/tools/checks.d.ts.map +1 -1
- package/dist/adapters/github/tools/checks.js +6 -17
- package/dist/adapters/github/tools/checks.js.map +1 -1
- package/dist/adapters/github/tools/issue.d.ts.map +1 -1
- package/dist/adapters/github/tools/issue.js +6 -17
- package/dist/adapters/github/tools/issue.js.map +1 -1
- package/dist/adapters/github/tools/pr.d.ts.map +1 -1
- package/dist/adapters/github/tools/pr.js +6 -17
- package/dist/adapters/github/tools/pr.js.map +1 -1
- package/dist/adapters/github/tools/read.d.ts.map +1 -1
- package/dist/adapters/github/tools/read.js +6 -17
- package/dist/adapters/github/tools/read.js.map +1 -1
- package/dist/adapters/github/tools/review-reply.d.ts.map +1 -1
- package/dist/adapters/github/tools/review-reply.js +6 -17
- package/dist/adapters/github/tools/review-reply.js.map +1 -1
- package/dist/adapters/github/tools/sync.d.ts.map +1 -1
- package/dist/adapters/github/tools/sync.js +6 -17
- package/dist/adapters/github/tools/sync.js.map +1 -1
- package/dist/adapters/slack/bot.js +1 -1
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/telegram/context.d.ts.map +1 -1
- package/dist/adapters/telegram/context.js +33 -151
- package/dist/adapters/telegram/context.js.map +1 -1
- package/dist/agent.d.ts +0 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +28 -32
- package/dist/agent.js.map +1 -1
- package/dist/cli/arg-grammar.d.ts +25 -0
- package/dist/cli/arg-grammar.d.ts.map +1 -0
- package/dist/cli/arg-grammar.js +59 -0
- package/dist/cli/arg-grammar.js.map +1 -0
- package/dist/cli/boot.d.ts +16 -0
- package/dist/cli/boot.d.ts.map +1 -0
- package/dist/cli/boot.js +119 -0
- package/dist/cli/boot.js.map +1 -0
- package/dist/cli/ext.js +9 -11
- package/dist/cli/ext.js.map +1 -1
- package/dist/commands/extensions.js +2 -2
- package/dist/commands/extensions.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +5 -2
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +8 -8
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/sandbox.d.ts.map +1 -1
- package/dist/commands/sandbox.js +7 -5
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/config.d.ts +0 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +8 -41
- package/dist/config.js.map +1 -1
- package/dist/env-manifest.d.ts +35 -0
- package/dist/env-manifest.d.ts.map +1 -0
- package/dist/env-manifest.js +225 -0
- package/dist/env-manifest.js.map +1 -0
- package/dist/events.d.ts +0 -10
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +9 -82
- package/dist/events.js.map +1 -1
- package/dist/execution-resolver.d.ts +1 -0
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +33 -36
- package/dist/execution-resolver.js.map +1 -1
- package/dist/harness/event-format.d.ts +66 -0
- package/dist/harness/event-format.d.ts.map +1 -0
- package/dist/harness/event-format.js +112 -0
- package/dist/harness/event-format.js.map +1 -0
- package/dist/harness/extensions/loader.d.ts +9 -6
- package/dist/harness/extensions/loader.d.ts.map +1 -1
- package/dist/harness/extensions/loader.js +35 -50
- package/dist/harness/extensions/loader.js.map +1 -1
- package/dist/harness/extensions/types.d.ts +10 -14
- package/dist/harness/extensions/types.d.ts.map +1 -1
- package/dist/harness/extensions/types.js.map +1 -1
- package/dist/harness/index.d.ts +1 -0
- package/dist/harness/index.d.ts.map +1 -1
- package/dist/harness/index.js +1 -0
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/runner.d.ts +16 -0
- package/dist/harness/runner.d.ts.map +1 -1
- package/dist/harness/runner.js +27 -1
- package/dist/harness/runner.js.map +1 -1
- package/dist/harness/subagent-runner.d.ts +18 -1
- package/dist/harness/subagent-runner.d.ts.map +1 -1
- package/dist/harness/subagent-runner.js +62 -30
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/main.js +69 -121
- package/dist/main.js.map +1 -1
- package/dist/observability/instrument.js +6 -4
- package/dist/observability/instrument.js.map +1 -1
- package/dist/observability/sentry.d.ts.map +1 -1
- package/dist/observability/sentry.js +3 -2
- package/dist/observability/sentry.js.map +1 -1
- package/dist/runtime/conversation-runtime.js +13 -3
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/types.d.ts +4 -0
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/sandbox/cloudflare.d.ts +1 -0
- package/dist/sandbox/cloudflare.d.ts.map +1 -1
- package/dist/sandbox/cloudflare.js +4 -1
- package/dist/sandbox/cloudflare.js.map +1 -1
- package/dist/sandbox/container.d.ts +1 -0
- package/dist/sandbox/container.d.ts.map +1 -1
- package/dist/sandbox/container.js +4 -1
- package/dist/sandbox/container.js.map +1 -1
- package/dist/sandbox/firecracker.d.ts +1 -0
- package/dist/sandbox/firecracker.d.ts.map +1 -1
- package/dist/sandbox/firecracker.js +4 -1
- package/dist/sandbox/firecracker.js.map +1 -1
- package/dist/sandbox/gondolin-bootstrap.d.ts +26 -0
- package/dist/sandbox/gondolin-bootstrap.d.ts.map +1 -0
- package/dist/sandbox/gondolin-bootstrap.js +27 -0
- package/dist/sandbox/gondolin-bootstrap.js.map +1 -0
- package/dist/sandbox/gondolin-contract.d.ts +125 -0
- package/dist/sandbox/gondolin-contract.d.ts.map +1 -0
- package/dist/sandbox/gondolin-contract.js +155 -0
- package/dist/sandbox/gondolin-contract.js.map +1 -0
- package/dist/sandbox/gondolin-fleet.d.ts +1 -1
- package/dist/sandbox/gondolin-fleet.d.ts.map +1 -1
- package/dist/sandbox/gondolin-fleet.js +1 -1
- package/dist/sandbox/gondolin-fleet.js.map +1 -1
- package/dist/sandbox/gondolin-gateway.d.ts +1 -0
- package/dist/sandbox/gondolin-gateway.d.ts.map +1 -1
- package/dist/sandbox/gondolin-gateway.js +13 -6
- package/dist/sandbox/gondolin-gateway.js.map +1 -1
- package/dist/sandbox/gondolin-inventory.d.ts +2 -16
- package/dist/sandbox/gondolin-inventory.d.ts.map +1 -1
- package/dist/sandbox/gondolin-inventory.js +2 -12
- package/dist/sandbox/gondolin-inventory.js.map +1 -1
- package/dist/sandbox/gondolin-placement.d.ts +0 -2
- package/dist/sandbox/gondolin-placement.d.ts.map +1 -1
- package/dist/sandbox/gondolin-placement.js +0 -6
- package/dist/sandbox/gondolin-placement.js.map +1 -1
- package/dist/sandbox/gondolin-recovery.d.ts +33 -0
- package/dist/sandbox/gondolin-recovery.d.ts.map +1 -0
- package/dist/sandbox/gondolin-recovery.js +39 -0
- package/dist/sandbox/gondolin-recovery.js.map +1 -0
- package/dist/sandbox/gondolin-remote.d.ts +2 -5
- package/dist/sandbox/gondolin-remote.d.ts.map +1 -1
- package/dist/sandbox/gondolin-remote.js +12 -39
- package/dist/sandbox/gondolin-remote.js.map +1 -1
- package/dist/sandbox/gondolin-worker-client.d.ts +8 -12
- package/dist/sandbox/gondolin-worker-client.d.ts.map +1 -1
- package/dist/sandbox/gondolin-worker-client.js +13 -15
- package/dist/sandbox/gondolin-worker-client.js.map +1 -1
- package/dist/sandbox/gondolin-worker.d.ts +2 -40
- package/dist/sandbox/gondolin-worker.d.ts.map +1 -1
- package/dist/sandbox/gondolin-worker.js.map +1 -1
- package/dist/sandbox/gondolin.d.ts +1 -0
- package/dist/sandbox/gondolin.d.ts.map +1 -1
- package/dist/sandbox/gondolin.js +8 -4
- package/dist/sandbox/gondolin.js.map +1 -1
- package/dist/sandbox/host.d.ts +1 -0
- package/dist/sandbox/host.d.ts.map +1 -1
- package/dist/sandbox/host.js +3 -0
- package/dist/sandbox/host.js.map +1 -1
- package/dist/sandbox/index.d.ts +9 -1
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +14 -0
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/types.d.ts +5 -0
- package/dist/sandbox/types.d.ts.map +1 -1
- package/dist/sandbox/types.js.map +1 -1
- package/dist/sandbox/utils.d.ts +1 -0
- package/dist/sandbox/utils.d.ts.map +1 -1
- package/dist/sandbox/utils.js +5 -2
- package/dist/sandbox/utils.js.map +1 -1
- package/dist/sessions/chat-history-sync.d.ts +32 -0
- package/dist/sessions/chat-history-sync.d.ts.map +1 -0
- package/dist/sessions/{agent-memory-file-manager.js → chat-history-sync.js} +24 -83
- package/dist/sessions/chat-history-sync.js.map +1 -0
- package/dist/sessions/conversation-log.d.ts +13 -0
- package/dist/sessions/conversation-log.d.ts.map +1 -0
- package/dist/sessions/conversation-log.js +47 -0
- package/dist/sessions/conversation-log.js.map +1 -0
- package/dist/sessions/rotation.d.ts +2 -0
- package/dist/sessions/rotation.d.ts.map +1 -0
- package/dist/sessions/rotation.js +39 -0
- package/dist/sessions/rotation.js.map +1 -0
- package/dist/sessions/store.d.ts.map +1 -1
- package/dist/sessions/store.js +4 -10
- package/dist/sessions/store.js.map +1 -1
- package/dist/sessions/types.d.ts +2 -2
- package/dist/sessions/types.d.ts.map +1 -1
- package/dist/sessions/types.js.map +1 -1
- package/dist/settings-mutation.d.ts +23 -0
- package/dist/settings-mutation.d.ts.map +1 -0
- package/dist/settings-mutation.js +42 -0
- package/dist/settings-mutation.js.map +1 -0
- package/dist/tools/event.d.ts.map +1 -1
- package/dist/tools/event.js +27 -46
- package/dist/tools/event.js.map +1 -1
- package/dist/tools/host-fn-tool.d.ts +21 -0
- package/dist/tools/host-fn-tool.d.ts.map +1 -0
- package/dist/tools/host-fn-tool.js +32 -0
- package/dist/tools/host-fn-tool.js.map +1 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +1 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/react.d.ts.map +1 -1
- package/dist/tools/react.js +6 -17
- package/dist/tools/react.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +7 -26
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/sandbox.d.ts.map +1 -1
- package/dist/tools/sandbox.js +5 -2
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/subagent-slots.d.ts +28 -0
- package/dist/tools/subagent-slots.d.ts.map +1 -0
- package/dist/tools/subagent-slots.js +57 -0
- package/dist/tools/subagent-slots.js.map +1 -0
- package/dist/tools/subagent.d.ts +7 -2
- package/dist/tools/subagent.d.ts.map +1 -1
- package/dist/tools/subagent.js +160 -111
- package/dist/tools/subagent.js.map +1 -1
- package/dist/tools/types.d.ts +10 -9
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/types.d.ts +5 -24
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/date.d.ts +1 -1
- package/dist/utils/date.js +1 -1
- package/dist/utils/date.js.map +1 -1
- package/dist/vault/disabled.d.ts.map +1 -1
- package/dist/vault/disabled.js +0 -1
- package/dist/vault/disabled.js.map +1 -1
- package/dist/vault/index.d.ts +0 -2
- package/dist/vault/index.d.ts.map +1 -1
- package/dist/vault/index.js +0 -10
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/injection.d.ts +20 -0
- package/dist/vault/injection.d.ts.map +1 -0
- package/dist/vault/injection.js +27 -0
- package/dist/vault/injection.js.map +1 -0
- package/dist/vault/types.d.ts +0 -2
- package/dist/vault/types.d.ts.map +1 -1
- package/dist/vault/types.js.map +1 -1
- package/dist/web/admin/portal.d.ts +3 -3
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +41 -39
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/admin/types.d.ts +3 -0
- package/dist/web/admin/types.d.ts.map +1 -1
- package/dist/web/admin/types.js.map +1 -1
- package/dist/web/agent-events/portal.d.ts.map +1 -1
- package/dist/web/agent-events/portal.js +2 -1
- package/dist/web/agent-events/portal.js.map +1 -1
- package/package.json +1 -1
- package/dist/sessions/agent-memory-file-manager.d.ts +0 -19
- package/dist/sessions/agent-memory-file-manager.d.ts.map +0 -1
- package/dist/sessions/agent-memory-file-manager.js.map +0 -1
- package/dist/vault/routing.d.ts +0 -4
- package/dist/vault/routing.d.ts.map +0 -1
- package/dist/vault/routing.js +0 -6
- package/dist/vault/routing.js.map +0 -1
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { isRecord, parseJsonValue, readTextFileIfExists } from "../utils/file-guards.js";
|
|
1
|
+
import { isRecord } from "../utils/file-guards.js";
|
|
3
2
|
import { isCommandText } from "../commands/text.js";
|
|
3
|
+
import { readConversationLog } from "./conversation-log.js";
|
|
4
4
|
import { formatHistoryLine, stripHistoryLinePrefix } from "./history-line.js";
|
|
5
|
-
import * as log from "../log.js";
|
|
6
5
|
import { isPlatformHistorySession } from "./metadata.js";
|
|
6
|
+
import { shouldRotateTopLevelSession } from "./rotation.js";
|
|
7
7
|
import { isThreadSessionKey } from "./session-key.js";
|
|
8
8
|
import { createManagedSessionFile, createManagedSessionFileAtPath, extractSessionSuffix, getChannelSessionDir, getThreadSessionFile, openManagedSession, resolveChannelSessionFile, tryResolveCurrentSession, tryResolveThreadSession, } from "./store.js";
|
|
9
9
|
const DEFAULT_RECENT_DAYS = 14;
|
|
10
10
|
const DEFAULT_MAX_TOP_LEVEL_MESSAGES = 200;
|
|
11
11
|
const CHAT_SYNC_CUSTOM_TYPE = "mikan.chat_sync";
|
|
12
|
-
const BIWEEKLY_ROTATION_ANCHOR = new Date(2026, 0, 4); // Sunday
|
|
13
|
-
const BIWEEKLY_MS = 14 * 24 * 60 * 60 * 1000;
|
|
14
12
|
export function hasMaterializedChatSession(options) {
|
|
15
13
|
if (!isThreadSessionKey(options.sessionKey)) {
|
|
16
14
|
return resolveChannelSessionFile(options.conversationDir) !== null;
|
|
@@ -40,7 +38,13 @@ export async function waitForThreadSessionBootstrap(options) {
|
|
|
40
38
|
}
|
|
41
39
|
return waited;
|
|
42
40
|
}
|
|
43
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Syncs the platform chat transcript (log.jsonl) into managed session files:
|
|
43
|
+
* resolves which session file a message belongs to (top-level vs thread,
|
|
44
|
+
* with biweekly rotation), bootstraps new sessions from recent history, and
|
|
45
|
+
* incrementally appends log messages the session does not yet represent.
|
|
46
|
+
*/
|
|
47
|
+
export class ChatHistorySync {
|
|
44
48
|
constructor(options = {}) {
|
|
45
49
|
this.recentDays = options.recentDays ?? DEFAULT_RECENT_DAYS;
|
|
46
50
|
this.maxTopLevelMessages = options.maxTopLevelMessages ?? DEFAULT_MAX_TOP_LEVEL_MESSAGES;
|
|
@@ -69,7 +73,7 @@ export class AgentMemoryFileManager {
|
|
|
69
73
|
}
|
|
70
74
|
syncSessionManager(options) {
|
|
71
75
|
const records = readConversationLog(options.conversationDir);
|
|
72
|
-
syncSessionManagerFromLog(options.sessionManager, selectExistingSessionSyncMessages(records, {
|
|
76
|
+
return syncSessionManagerFromLog(options.sessionManager, selectExistingSessionSyncMessages(records, {
|
|
73
77
|
sessionKey: isThreadSessionKey(options.sessionKey) ? options.sessionKey : null,
|
|
74
78
|
excludeMessageId: options.currentMessageId,
|
|
75
79
|
}), this.historyWindow());
|
|
@@ -136,74 +140,6 @@ export class AgentMemoryFileManager {
|
|
|
136
140
|
return { sessionDir: options.sessionDir, contextFile: threadFile, threadRootMessage };
|
|
137
141
|
}
|
|
138
142
|
}
|
|
139
|
-
function shouldRotateTopLevelSession(sessionFile, now) {
|
|
140
|
-
const timestamp = readSessionTimestamp(sessionFile);
|
|
141
|
-
return timestamp !== null && biweeklyBucket(timestamp) !== biweeklyBucket(now);
|
|
142
|
-
}
|
|
143
|
-
function readSessionTimestamp(sessionFile) {
|
|
144
|
-
const raw = readTextFileIfExists(sessionFile);
|
|
145
|
-
if (raw === undefined)
|
|
146
|
-
return null;
|
|
147
|
-
const firstLine = raw.split("\n").find((line) => line.trim());
|
|
148
|
-
if (!firstLine)
|
|
149
|
-
return null;
|
|
150
|
-
try {
|
|
151
|
-
const header = parseJsonValue(firstLine, (value) => isRecord(value), (detail) => (detail === "unexpected JSON shape" ? "expected a JSON object" : detail));
|
|
152
|
-
if (typeof header.timestamp !== "string")
|
|
153
|
-
return null;
|
|
154
|
-
const date = new Date(header.timestamp);
|
|
155
|
-
return Number.isFinite(date.getTime()) ? date : null;
|
|
156
|
-
}
|
|
157
|
-
catch {
|
|
158
|
-
return null;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
function biweeklyBucket(date) {
|
|
162
|
-
const weekStart = sundayStart(date).getTime();
|
|
163
|
-
const anchor = sundayStart(BIWEEKLY_ROTATION_ANCHOR).getTime();
|
|
164
|
-
return Math.floor((weekStart - anchor) / BIWEEKLY_MS);
|
|
165
|
-
}
|
|
166
|
-
function sundayStart(date) {
|
|
167
|
-
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
|
|
168
|
-
}
|
|
169
|
-
function readConversationLog(conversationDir) {
|
|
170
|
-
const logFile = join(conversationDir, "log.jsonl");
|
|
171
|
-
const raw = readTextFileIfExists(logFile);
|
|
172
|
-
if (raw === undefined)
|
|
173
|
-
return [];
|
|
174
|
-
const lines = raw.trim().split("\n").filter(Boolean);
|
|
175
|
-
const records = [];
|
|
176
|
-
for (let i = 0; i < lines.length; i++) {
|
|
177
|
-
try {
|
|
178
|
-
const message = parseJsonValue(lines[i], (value) => isRecord(value), (detail) => (detail === "unexpected JSON shape" ? "expected a JSON object" : detail));
|
|
179
|
-
records.push({ message, index: i });
|
|
180
|
-
}
|
|
181
|
-
catch (err) {
|
|
182
|
-
log.logWarning(`Skipping malformed log entry at ${logFile}:${i + 1}`, err instanceof Error ? err.message : String(err));
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
return coalesceMessagingBotLogChunks(records);
|
|
186
|
-
}
|
|
187
|
-
function coalesceMessagingBotLogChunks(records) {
|
|
188
|
-
const coalesced = [];
|
|
189
|
-
for (const record of records) {
|
|
190
|
-
const previous = coalesced.at(-1);
|
|
191
|
-
if (previous && canCoalesceMessagingBotLogChunk(previous.message, record.message)) {
|
|
192
|
-
previous.message.text = `${previous.message.text ?? ""}${record.message.text ?? ""}`;
|
|
193
|
-
continue;
|
|
194
|
-
}
|
|
195
|
-
coalesced.push({ ...record, message: { ...record.message } });
|
|
196
|
-
}
|
|
197
|
-
return coalesced;
|
|
198
|
-
}
|
|
199
|
-
function canCoalesceMessagingBotLogChunk(previous, current) {
|
|
200
|
-
return (previous.isMessagingBot === true &&
|
|
201
|
-
current.isMessagingBot === true &&
|
|
202
|
-
!!previous.ts &&
|
|
203
|
-
previous.ts === current.ts &&
|
|
204
|
-
previous.threadTs === current.threadTs &&
|
|
205
|
-
previous.user === current.user);
|
|
206
|
-
}
|
|
207
143
|
function findLogRecordById(records, messageId) {
|
|
208
144
|
for (let i = records.length - 1; i >= 0; i--) {
|
|
209
145
|
if (records[i].message.ts === messageId)
|
|
@@ -308,32 +244,37 @@ function bootstrapSessionFromLog(sessionFile, cwd, records, lastMessageId = reco
|
|
|
308
244
|
}
|
|
309
245
|
function syncSessionFromLog(sessionFile, cwd, records, historyWindow) {
|
|
310
246
|
if (records.length === 0)
|
|
311
|
-
return;
|
|
312
|
-
syncSessionManagerFromLog(openManagedSession(sessionFile, cwd), records, historyWindow);
|
|
247
|
+
return { appended: 0 };
|
|
248
|
+
return syncSessionManagerFromLog(openManagedSession(sessionFile, cwd), records, historyWindow);
|
|
313
249
|
}
|
|
314
250
|
function syncSessionManagerFromLog(sessionManager, records, historyWindow) {
|
|
315
251
|
if (records.length === 0)
|
|
316
|
-
return;
|
|
252
|
+
return { appended: 0 };
|
|
317
253
|
const existingEntries = sessionManager.getEntries();
|
|
318
254
|
const lastSyncedMessageId = getLatestChatSyncMessageId(existingEntries);
|
|
319
255
|
const lastSyncedIndex = lastSyncedMessageId
|
|
320
256
|
? records.findIndex((record) => record.message.ts === lastSyncedMessageId)
|
|
321
257
|
: -1;
|
|
322
258
|
if (lastSyncedMessageId && lastSyncedIndex === -1)
|
|
323
|
-
return;
|
|
259
|
+
return { appended: 0 };
|
|
324
260
|
const syncCandidates = selectRecentMessages(records.slice(lastSyncedIndex + 1), historyWindow);
|
|
325
261
|
if (syncCandidates.length === 0)
|
|
326
|
-
return;
|
|
262
|
+
return { appended: 0 };
|
|
327
263
|
const represented = buildRepresentedMessageCounts(existingEntries);
|
|
328
264
|
const newRecords = syncCandidates.filter((record) => !consumeRepresentedLogMessage(record, represented));
|
|
329
265
|
if (newRecords.length === 0)
|
|
330
|
-
return;
|
|
266
|
+
return { appended: 0 };
|
|
267
|
+
const lastMessageId = syncCandidates.at(-1)?.message.ts;
|
|
331
268
|
appendLogRecordsToSession(sessionManager, newRecords);
|
|
332
269
|
sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {
|
|
333
270
|
source: "log.jsonl",
|
|
334
271
|
messageCount: newRecords.length,
|
|
335
|
-
lastMessageId
|
|
272
|
+
lastMessageId,
|
|
336
273
|
});
|
|
274
|
+
return {
|
|
275
|
+
appended: newRecords.length,
|
|
276
|
+
...(lastMessageId !== undefined ? { lastMessageId } : {}),
|
|
277
|
+
};
|
|
337
278
|
}
|
|
338
279
|
function appendLogRecordsToSession(sessionManager, records) {
|
|
339
280
|
for (const record of records) {
|
|
@@ -467,4 +408,4 @@ function zeroUsage() {
|
|
|
467
408
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
468
409
|
};
|
|
469
410
|
}
|
|
470
|
-
//# sourceMappingURL=
|
|
411
|
+
//# sourceMappingURL=chat-history-sync.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-history-sync.js","sourceRoot":"","sources":["../../src/sessions/chat-history-sync.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAkB,MAAM,uBAAuB,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EACL,wBAAwB,EACxB,8BAA8B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AI,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 type { ConversationLogMessage } from \"../types.js\";\nimport { isRecord } from \"../utils/file-guards.js\";\nimport { isCommandText } from \"../commands/text.js\";\nimport { readConversationLog, type LogRecord } from \"./conversation-log.js\";\nimport { formatHistoryLine, stripHistoryLinePrefix } from \"./history-line.js\";\nimport { isPlatformHistorySession } from \"./metadata.js\";\nimport { shouldRotateTopLevelSession } from \"./rotation.js\";\nimport { isThreadSessionKey } from \"./session-key.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\";\n\ntype SessionAppendMessage = Parameters<SessionStore[\"appendMessage\"]>[0];\n\nexport type {\n ChatHistorySyncOptions,\n HasMaterializedSessionOptions,\n RegisterThreadSessionOptions,\n ResetChatSessionOptions,\n ResolveChatSessionScopeOptions,\n SyncChatSessionOptions,\n ThreadBootstrapWaitOptions,\n} from \"./types.js\";\nimport type {\n ChatHistorySyncOptions,\n HasMaterializedSessionOptions,\n RegisterThreadSessionOptions,\n ResetChatSessionOptions,\n ResolveChatSessionScopeOptions,\n SyncChatSessionOptions,\n ThreadBootstrapWaitOptions,\n} from \"./types.js\";\n\n/** What one sync pass actually did — the inspectable result of a sync. */\nexport interface ChatSyncReport {\n /** Log messages appended to the session in this pass. */\n appended: number;\n /** The log message id recorded as the new sync watermark. */\n lastMessageId?: string;\n}\n\nexport function hasMaterializedChatSession(options: HasMaterializedSessionOptions): boolean {\n if (!isThreadSessionKey(options.sessionKey)) {\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 (!isThreadSessionKey(options.sessionKey)) 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 (!isThreadSessionKey(sessionKey)) 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\n/**\n * Syncs the platform chat transcript (log.jsonl) into managed session files:\n * resolves which session file a message belongs to (top-level vs thread,\n * with biweekly rotation), bootstraps new sessions from recent history, and\n * incrementally appends log messages the session does not yet represent.\n */\nexport class ChatHistorySync {\n private readonly recentDays: number;\n private readonly maxTopLevelMessages: number;\n private readonly now: () => Date;\n\n constructor(options: ChatHistorySyncOptions = {}) {\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 (!isThreadSessionKey(options.sessionKey)) {\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: SyncChatSessionOptions): ChatSyncReport {\n const records = readConversationLog(options.conversationDir);\n return syncSessionManagerFromLog(\n options.sessionManager,\n selectExistingSessionSyncMessages(records, {\n sessionKey: isThreadSessionKey(options.sessionKey) ? 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 (isThreadSessionKey(options.sessionKey)) {\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 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 return !message.isMessagingBot && isCommandText(message.text ?? \"\");\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}\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): ChatSyncReport {\n if (records.length === 0) return { appended: 0 };\n return syncSessionManagerFromLog(openManagedSession(sessionFile, cwd), records, historyWindow);\n}\n\nfunction syncSessionManagerFromLog(\n sessionManager: SessionStore,\n records: LogRecord[],\n historyWindow: HistoryWindow,\n): ChatSyncReport {\n if (records.length === 0) return { appended: 0 };\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 { appended: 0 };\n\n const syncCandidates = selectRecentMessages(records.slice(lastSyncedIndex + 1), historyWindow);\n if (syncCandidates.length === 0) return { appended: 0 };\n\n const represented = buildRepresentedMessageCounts(existingEntries);\n const newRecords = syncCandidates.filter(\n (record) => !consumeRepresentedLogMessage(record, represented),\n );\n if (newRecords.length === 0) return { appended: 0 };\n\n const lastMessageId = syncCandidates.at(-1)?.message.ts;\n appendLogRecordsToSession(sessionManager, newRecords);\n sessionManager.appendCustomEntry(CHAT_SYNC_CUSTOM_TYPE, {\n source: \"log.jsonl\",\n messageCount: newRecords.length,\n lastMessageId,\n });\n return {\n appended: newRecords.length,\n ...(lastMessageId !== undefined ? { lastMessageId } : {}),\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 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\nconst normalizeComparableText = stripHistoryLinePrefix;\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 return formatHistoryLine({\n date: message.date ? new Date(message.date) : undefined,\n userName: message.userName || message.user,\n text: message.text?.trim() ?? \"\",\n });\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"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ConversationLogMessage } from "../types.js";
|
|
2
|
+
/** One parsed log.jsonl entry with its original line index. */
|
|
3
|
+
export interface LogRecord {
|
|
4
|
+
message: ConversationLogMessage;
|
|
5
|
+
index: number;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Read a conversation's platform chat log (log.jsonl): skip malformed lines,
|
|
9
|
+
* and coalesce consecutive messaging-bot chunks that share a ts — streamed
|
|
10
|
+
* responses are logged in pieces but represent one message.
|
|
11
|
+
*/
|
|
12
|
+
export declare function readConversationLog(conversationDir: string): LogRecord[];
|
|
13
|
+
//# sourceMappingURL=conversation-log.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-log.d.ts","sourceRoot":"","sources":["../../src/sessions/conversation-log.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAG1D,+DAA+D;AAC/D,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,sBAAsB,CAAC;IAChC,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,eAAe,EAAE,MAAM,GAAG,SAAS,EAAE,CAuBxE"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { join } from "path";
|
|
2
|
+
import * as log from "../log.js";
|
|
3
|
+
import { isRecord, parseJsonValue, readTextFileIfExists } from "../utils/file-guards.js";
|
|
4
|
+
/**
|
|
5
|
+
* Read a conversation's platform chat log (log.jsonl): skip malformed lines,
|
|
6
|
+
* and coalesce consecutive messaging-bot chunks that share a ts — streamed
|
|
7
|
+
* responses are logged in pieces but represent one message.
|
|
8
|
+
*/
|
|
9
|
+
export function readConversationLog(conversationDir) {
|
|
10
|
+
const logFile = join(conversationDir, "log.jsonl");
|
|
11
|
+
const raw = readTextFileIfExists(logFile);
|
|
12
|
+
if (raw === undefined)
|
|
13
|
+
return [];
|
|
14
|
+
const lines = raw.trim().split("\n").filter(Boolean);
|
|
15
|
+
const records = [];
|
|
16
|
+
for (let i = 0; i < lines.length; i++) {
|
|
17
|
+
try {
|
|
18
|
+
const message = parseJsonValue(lines[i], (value) => isRecord(value), (detail) => (detail === "unexpected JSON shape" ? "expected a JSON object" : detail));
|
|
19
|
+
records.push({ message, index: i });
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
log.logWarning(`Skipping malformed log entry at ${logFile}:${i + 1}`, err instanceof Error ? err.message : String(err));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return coalesceMessagingBotLogChunks(records);
|
|
26
|
+
}
|
|
27
|
+
function coalesceMessagingBotLogChunks(records) {
|
|
28
|
+
const coalesced = [];
|
|
29
|
+
for (const record of records) {
|
|
30
|
+
const previous = coalesced.at(-1);
|
|
31
|
+
if (previous && canCoalesceMessagingBotLogChunk(previous.message, record.message)) {
|
|
32
|
+
previous.message.text = `${previous.message.text ?? ""}${record.message.text ?? ""}`;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
coalesced.push({ ...record, message: { ...record.message } });
|
|
36
|
+
}
|
|
37
|
+
return coalesced;
|
|
38
|
+
}
|
|
39
|
+
function canCoalesceMessagingBotLogChunk(previous, current) {
|
|
40
|
+
return (previous.isMessagingBot === true &&
|
|
41
|
+
current.isMessagingBot === true &&
|
|
42
|
+
!!previous.ts &&
|
|
43
|
+
previous.ts === current.ts &&
|
|
44
|
+
previous.threadTs === current.threadTs &&
|
|
45
|
+
previous.user === current.user);
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=conversation-log.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-log.js","sourceRoot":"","sources":["../../src/sessions/conversation-log.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAQzF;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,eAAuB;IACzD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,EAAE,WAAW,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAC1C,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IAEjC,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACrD,MAAM,OAAO,GAAgB,EAAE,CAAC;IAChC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,IAAI,CAAC;YACH,MAAM,OAAO,GAAG,cAAc,CAC5B,KAAK,CAAC,CAAC,CAAC,EACR,CAAC,KAAK,EAAmC,EAAE,CAAC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AE/B,OAAO,CACL,QAAQ,CAAC,cAAc,KAAK,IAAI;QAChC,OAAO,CAAC,cAAc,KAAK,IAAI;QAC/B,CAAC,CAAC,QAAQ,CAAC,EAAE;QACb,QAAQ,CAAC,EAAE,KAAK,OAAO,CAAC,EAAE;QAC1B,QAAQ,CAAC,QAAQ,KAAK,OAAO,CAAC,QAAQ;QACtC,QAAQ,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI,CAC/B,CAAC;AACJ,CAAC","sourcesContent":["import { join } from \"path\";\nimport * as log from \"../log.js\";\nimport type { ConversationLogMessage } from \"../types.js\";\nimport { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\n\n/** One parsed log.jsonl entry with its original line index. */\nexport interface LogRecord {\n message: ConversationLogMessage;\n index: number;\n}\n\n/**\n * Read a conversation's platform chat log (log.jsonl): skip malformed lines,\n * and coalesce consecutive messaging-bot chunks that share a ts — streamed\n * responses are logged in pieces but represent one message.\n */\nexport function 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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rotation.d.ts","sourceRoot":"","sources":["../../src/sessions/rotation.ts"],"names":[],"mappings":"AAWA,wBAAgB,2BAA2B,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAGnF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { isRecord, parseJsonValue, readTextFileIfExists } from "../utils/file-guards.js";
|
|
2
|
+
/**
|
|
3
|
+
* Biweekly rotation clock for top-level shared sessions: a session file
|
|
4
|
+
* rotates when its header timestamp falls in a different two-week bucket
|
|
5
|
+
* (anchored to a fixed Sunday) than the given "now".
|
|
6
|
+
*/
|
|
7
|
+
const BIWEEKLY_ROTATION_ANCHOR = new Date(2026, 0, 4); // Sunday
|
|
8
|
+
const BIWEEKLY_MS = 14 * 24 * 60 * 60 * 1000;
|
|
9
|
+
export function shouldRotateTopLevelSession(sessionFile, now) {
|
|
10
|
+
const timestamp = readSessionTimestamp(sessionFile);
|
|
11
|
+
return timestamp !== null && biweeklyBucket(timestamp) !== biweeklyBucket(now);
|
|
12
|
+
}
|
|
13
|
+
function readSessionTimestamp(sessionFile) {
|
|
14
|
+
const raw = readTextFileIfExists(sessionFile);
|
|
15
|
+
if (raw === undefined)
|
|
16
|
+
return null;
|
|
17
|
+
const firstLine = raw.split("\n").find((line) => line.trim());
|
|
18
|
+
if (!firstLine)
|
|
19
|
+
return null;
|
|
20
|
+
try {
|
|
21
|
+
const header = parseJsonValue(firstLine, (value) => isRecord(value), (detail) => (detail === "unexpected JSON shape" ? "expected a JSON object" : detail));
|
|
22
|
+
if (typeof header.timestamp !== "string")
|
|
23
|
+
return null;
|
|
24
|
+
const date = new Date(header.timestamp);
|
|
25
|
+
return Number.isFinite(date.getTime()) ? date : null;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function biweeklyBucket(date) {
|
|
32
|
+
const weekStart = sundayStart(date).getTime();
|
|
33
|
+
const anchor = sundayStart(BIWEEKLY_ROTATION_ANCHOR).getTime();
|
|
34
|
+
return Math.floor((weekStart - anchor) / BIWEEKLY_MS);
|
|
35
|
+
}
|
|
36
|
+
function sundayStart(date) {
|
|
37
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=rotation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rotation.js","sourceRoot":"","sources":["../../src/sessions/rotation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAEzF;;;;GAIG;AAEH,MAAM,wBAAwB,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS;AAChE,MAAM,WAAW,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,UAAU,2BAA2B,CAAC,WAAmB,EAAE,GAAS;IACxE,MAAM,SAAS,GAAG,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACpD,OAAO,SAAS,KAAK,IAAI,IAAI,cAAc,CAAC,SAAS,CAAC,KAAK,cAAc,CAAC,GAAG,CAAC,CAAC;AACjF,CAAC;AAED,SAAS,oBAAoB,CAAC,WAAmB;IAC/C,MAAM,GAAG,GAAG,oBAAoB,CAAC,WAAW,CAAC,CAAC;IAC9C,IAAI,GAAG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I,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;AACvF,CAAC","sourcesContent":["import { isRecord, parseJsonValue, readTextFileIfExists } from \"../utils/file-guards.js\";\n\n/**\n * Biweekly rotation clock for top-level shared sessions: a session file\n * rotates when its header timestamp falls in a different two-week bucket\n * (anchored to a fixed Sunday) than the given \"now\".\n */\n\nconst BIWEEKLY_ROTATION_ANCHOR = new Date(2026, 0, 4); // Sunday\nconst BIWEEKLY_MS = 14 * 24 * 60 * 60 * 1000;\n\nexport function 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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/sessions/store.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAKnD,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC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,GAAG,EAAE,MAAM,GAAG,MAAM,CAIjF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE9D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAO/D;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAOhF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,CAMjF;AAaD;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGvF;AASD;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAEnF;AAkDD;;;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"}
|
package/dist/sessions/store.js
CHANGED
|
@@ -104,16 +104,10 @@ export function createManagedSessionFileAtPath(sessionFile, cwd) {
|
|
|
104
104
|
return sessionFile;
|
|
105
105
|
}
|
|
106
106
|
function writeSessionHeader(sessionFile, cwd, sessionId = randomUUID()) {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
version: 3,
|
|
112
|
-
id: sessionId,
|
|
113
|
-
timestamp: new Date().toISOString(),
|
|
114
|
-
cwd,
|
|
115
|
-
};
|
|
116
|
-
atomicWritePrivateFile(sessionFile, `${JSON.stringify(header)}\n`);
|
|
107
|
+
mkdirSync(dirname(sessionFile), { recursive: true });
|
|
108
|
+
// The header format (and its version) is owned by the harness store; this
|
|
109
|
+
// layer only decides the path and the id.
|
|
110
|
+
SessionStore.create(sessionFile, cwd, { id: sessionId });
|
|
117
111
|
}
|
|
118
112
|
/**
|
|
119
113
|
* Returns the fixed session file path for a Slack thread.
|
|
@@ -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,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;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD;;;;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,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AI,gBAAgB,CAAC,QAAQ,CAAC;QAAE,OAAO,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\";\nimport { threadSuffixOf } from \"./session-key.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 return threadSuffixOf(sessionKey) ?? 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"]}
|
|
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;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAkB;IACrD,OAAO,IAAI,CAAC,UAAU,EAAE,UAAU,CAAC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AAC;IACnD,IAAI,QAAQ,IAAI,UAAU,CAAC,QAAQ,CAAC,IAAI,gBAAgB,CAAC,QAAQ,CAAC;QAAE,OAAO,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\";\nimport { threadSuffixOf } from \"./session-key.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 return threadSuffixOf(sessionKey) ?? 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 mkdirSync(dirname(sessionFile), { recursive: true });\n // The header format (and its version) is owned by the harness store; this\n // layer only decides the path and the id.\n SessionStore.create(sessionFile, cwd, { id: sessionId });\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"]}
|
package/dist/sessions/types.d.ts
CHANGED
|
@@ -32,7 +32,7 @@ export interface ResolvedSessionScope {
|
|
|
32
32
|
contextFile: string;
|
|
33
33
|
threadRootMessage: ThreadRootMessage | null;
|
|
34
34
|
}
|
|
35
|
-
export interface
|
|
35
|
+
export interface ChatHistorySyncOptions {
|
|
36
36
|
recentDays?: number;
|
|
37
37
|
maxTopLevelMessages?: number;
|
|
38
38
|
now?: () => Date;
|
|
@@ -46,7 +46,7 @@ export interface ResolveChatSessionScopeOptions {
|
|
|
46
46
|
/** Rotate top-level shared sessions on biweekly Sunday boundaries. */
|
|
47
47
|
rotateTopLevelSession?: boolean;
|
|
48
48
|
}
|
|
49
|
-
export interface
|
|
49
|
+
export interface SyncChatSessionOptions {
|
|
50
50
|
conversationDir: string;
|
|
51
51
|
sessionKey: string;
|
|
52
52
|
sessionManager: import("../harness/index.js").SessionStore;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"AAAA,O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,CAAC,EAAE,MAAM,CAAC;IAC1B,sEAAsE;IACtE,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED,MAAM,WAAW,sBAAsB;IACrC,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,OAAO,qBAAqB,EAAE,YAAY,CAAC;IAC3D,4FAA4F;IAC5F,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,uBAAuB;IACtC,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,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
|
|
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 history sync ────────────────────────────────────────────────────────\n\nexport interface ChatHistorySyncOptions {\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 SyncChatSessionOptions {\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"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { AgentConfig } from "./types.js";
|
|
2
|
+
/** The runner-cache slice of the conversation runtime this seam needs. */
|
|
3
|
+
export interface RunnerCacheControl {
|
|
4
|
+
switchConversationModel(conversationId: string, provider: string, model: string): boolean;
|
|
5
|
+
}
|
|
6
|
+
export interface GlobalRunnerCacheControl {
|
|
7
|
+
refreshAllConversations(): {
|
|
8
|
+
busy: string[];
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export type SettingsApplyResult = {
|
|
12
|
+
ok: true;
|
|
13
|
+
runtimeSwitched: boolean | null;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
reason: "busy";
|
|
17
|
+
};
|
|
18
|
+
export declare function applyConversationSettings(runtime: RunnerCacheControl | undefined, workingDir: string, conversationId: string, patch: Partial<AgentConfig>): SettingsApplyResult;
|
|
19
|
+
export declare function applyGlobalSettings(runtime: GlobalRunnerCacheControl | undefined, patch: Partial<AgentConfig>): {
|
|
20
|
+
ok: true;
|
|
21
|
+
staleConversations: string[];
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=settings-mutation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settings-mutation.d.ts","sourceRoot":"","sources":["../src/settings-mutation.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,0EAA0E;AAC1E,MAAM,WAAW,kBAAkB;IACjC,uBAAuB,CAAC,cAAc,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CAC3F;AAED,MAAM,WAAW,wBAAwB;IACvC,uBAAuB,IAAI;QAAE,IAAI,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;CAC/C;AAED,MAAM,MAAM,mBAAmB,GAC3B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,eAAe,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,GAC7C;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AASlC,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,kBAAkB,GAAG,SAAS,EACvC,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,GAC1B,mBAAmB,CAYrB;AAED,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,wBAAwB,GAAG,SAAS,EAC7C,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,GAC1B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,kBAAkB,EAAE,MAAM,EAAE,CAAA;CAAE,CAK5C"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one writer seam for settings mutations that affect live conversations.
|
|
3
|
+
* Chat commands (/model, /sandbox) and the Admin portal are adapters here;
|
|
4
|
+
* none of them call updateConversationSettings/updateGlobalSettings directly
|
|
5
|
+
* for these keys anymore.
|
|
6
|
+
*
|
|
7
|
+
* Policy, uniform across all adapters:
|
|
8
|
+
* - llm.* changes bake into cached session runners, so a conversation-scoped
|
|
9
|
+
* change clears the conversation's cached runners BEFORE writing — and
|
|
10
|
+
* refuses (no write, no clear) while the conversation has a running job.
|
|
11
|
+
* Disk and cache never disagree.
|
|
12
|
+
* - Other keys (sandbox mount, slack replyMode, limits) are re-read at use
|
|
13
|
+
* time and write without touching runners.
|
|
14
|
+
* - Global changes always write (the Admin default surface), then clear every
|
|
15
|
+
* idle conversation's cached runners; conversations that were busy keep
|
|
16
|
+
* their old runner until it ends and are reported as stale.
|
|
17
|
+
*/
|
|
18
|
+
import { join } from "path";
|
|
19
|
+
import { updateConversationSettings, updateGlobalSettings } from "./config.js";
|
|
20
|
+
/** True when a patch touches keys a cached session runner bakes in. */
|
|
21
|
+
function affectsCachedRunner(patch) {
|
|
22
|
+
return (patch.provider !== undefined || patch.model !== undefined || patch.thinkingLevel !== undefined);
|
|
23
|
+
}
|
|
24
|
+
export function applyConversationSettings(runtime, workingDir, conversationId, patch) {
|
|
25
|
+
let runtimeSwitched = null;
|
|
26
|
+
if (affectsCachedRunner(patch) && runtime) {
|
|
27
|
+
// Clear-or-refuse before writing. The clear and the write happen in the
|
|
28
|
+
// same synchronous tick, so no runner can be created in between.
|
|
29
|
+
if (!runtime.switchConversationModel(conversationId, patch.provider ?? "", patch.model ?? "")) {
|
|
30
|
+
return { ok: false, reason: "busy" };
|
|
31
|
+
}
|
|
32
|
+
runtimeSwitched = true;
|
|
33
|
+
}
|
|
34
|
+
updateConversationSettings(join(workingDir, conversationId), patch);
|
|
35
|
+
return { ok: true, runtimeSwitched };
|
|
36
|
+
}
|
|
37
|
+
export function applyGlobalSettings(runtime, patch) {
|
|
38
|
+
updateGlobalSettings(patch);
|
|
39
|
+
const staleConversations = affectsCachedRunner(patch) && runtime ? runtime.refreshAllConversations().busy : [];
|
|
40
|
+
return { ok: true, staleConversations };
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=settings-mutation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settings-mutation.js","sourceRoot":"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C,CAAC,EAAE,CAAC;IACtF,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * The one writer seam for settings mutations that affect live conversations.\n * Chat commands (/model, /sandbox) and the Admin portal are adapters here;\n * none of them call updateConversationSettings/updateGlobalSettings directly\n * for these keys anymore.\n *\n * Policy, uniform across all adapters:\n * - llm.* changes bake into cached session runners, so a conversation-scoped\n * change clears the conversation's cached runners BEFORE writing — and\n * refuses (no write, no clear) while the conversation has a running job.\n * Disk and cache never disagree.\n * - Other keys (sandbox mount, slack replyMode, limits) are re-read at use\n * time and write without touching runners.\n * - Global changes always write (the Admin default surface), then clear every\n * idle conversation's cached runners; conversations that were busy keep\n * their old runner until it ends and are reported as stale.\n */\nimport { join } from \"path\";\nimport { updateConversationSettings, updateGlobalSettings } from \"./config.js\";\nimport type { AgentConfig } from \"./types.js\";\n\n/** The runner-cache slice of the conversation runtime this seam needs. */\nexport interface RunnerCacheControl {\n switchConversationModel(conversationId: string, provider: string, model: string): boolean;\n}\n\nexport interface GlobalRunnerCacheControl {\n refreshAllConversations(): { busy: string[] };\n}\n\nexport type SettingsApplyResult =\n | { ok: true; runtimeSwitched: boolean | null }\n | { ok: false; reason: \"busy\" };\n\n/** True when a patch touches keys a cached session runner bakes in. */\nfunction affectsCachedRunner(patch: Partial<AgentConfig>): boolean {\n return (\n patch.provider !== undefined || patch.model !== undefined || patch.thinkingLevel !== undefined\n );\n}\n\nexport function applyConversationSettings(\n runtime: RunnerCacheControl | undefined,\n workingDir: string,\n conversationId: string,\n patch: Partial<AgentConfig>,\n): SettingsApplyResult {\n let runtimeSwitched: boolean | null = null;\n if (affectsCachedRunner(patch) && runtime) {\n // Clear-or-refuse before writing. The clear and the write happen in the\n // same synchronous tick, so no runner can be created in between.\n if (!runtime.switchConversationModel(conversationId, patch.provider ?? \"\", patch.model ?? \"\")) {\n return { ok: false, reason: \"busy\" };\n }\n runtimeSwitched = true;\n }\n updateConversationSettings(join(workingDir, conversationId), patch);\n return { ok: true, runtimeSwitched };\n}\n\nexport function applyGlobalSettings(\n runtime: GlobalRunnerCacheControl | undefined,\n patch: Partial<AgentConfig>,\n): { ok: true; staleConversations: string[] } {\n updateGlobalSettings(patch);\n const staleConversations =\n affectsCachedRunner(patch) && runtime ? runtime.refreshAllConversations().busy : [];\n return { ok: true, staleConversations };\n}\n"]}
|