somora 2026.930.1
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/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
// Filesystem session storage. Layout under SOMORA_HOME (default ~/.somora):
|
|
2
|
+
//
|
|
3
|
+
// agents/<agent>/sessions/
|
|
4
|
+
// main.jsonl ← magic, always conceptually present
|
|
5
|
+
// main.meta.json
|
|
6
|
+
// 20260430-143022_projekt-x.jsonl ← additional sessions
|
|
7
|
+
// 20260430-143022_projekt-x.meta.json
|
|
8
|
+
//
|
|
9
|
+
// JSONL = one NormalizedEvent per line (append-only, never rewritten).
|
|
10
|
+
// Meta JSON = free-form per-session metadata (engine session-id, slug,
|
|
11
|
+
// createdAt, future stats).
|
|
12
|
+
//
|
|
13
|
+
// Session resolution (DECISIONS #13):
|
|
14
|
+
// ref === "main" → "main" (always returned, even if file missing)
|
|
15
|
+
// ref matches exact-id → that exact id (404 if file missing)
|
|
16
|
+
// ref is a slug → newest existing file with that slug (404 if none)
|
|
17
|
+
|
|
18
|
+
import { access, appendFile, mkdir, readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { homedir } from 'node:os';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
import type { SessionMeta, SessionMetaStore } from '../engine/types.ts';
|
|
22
|
+
import type { NormalizedEvent } from '../types/events.ts';
|
|
23
|
+
|
|
24
|
+
const EXACT_ID_PATTERN = /^\d{8}-\d{6}_[A-Za-z0-9_-]+$/;
|
|
25
|
+
const VALID_SLUG = /^[A-Za-z0-9_-]+$/;
|
|
26
|
+
|
|
27
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
28
|
+
|
|
29
|
+
const VALID_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/;
|
|
30
|
+
|
|
31
|
+
function sanitize(name: string, kind: 'agent' | 'session'): string {
|
|
32
|
+
if (!VALID_NAME.test(name)) {
|
|
33
|
+
throw new Error(`invalid ${kind} name: ${JSON.stringify(name)}`);
|
|
34
|
+
}
|
|
35
|
+
return name;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function sessionDir(agent: string): string {
|
|
39
|
+
return join(SOMORA_HOME, 'agents', sanitize(agent, 'agent'), 'sessions');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function jsonlPath(agent: string, session: string): string {
|
|
43
|
+
return join(sessionDir(agent), `${sanitize(session, 'session')}.jsonl`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function metaPath(agent: string, session: string): string {
|
|
47
|
+
return join(sessionDir(agent), `${sanitize(session, 'session')}.meta.json`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function ensureDir(agent: string): Promise<void> {
|
|
51
|
+
await mkdir(sessionDir(agent), { recursive: true });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isEnoent(err: unknown): boolean {
|
|
55
|
+
return typeof err === 'object' && err !== null && (err as NodeJS.ErrnoException).code === 'ENOENT';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function getHistory(agent: string, session: string): Promise<NormalizedEvent[]> {
|
|
59
|
+
let raw: string;
|
|
60
|
+
try {
|
|
61
|
+
raw = await readFile(jsonlPath(agent, session), 'utf8');
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (isEnoent(err)) return [];
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
const events: NormalizedEvent[] = [];
|
|
67
|
+
for (const line of raw.split('\n')) {
|
|
68
|
+
if (!line.trim()) continue;
|
|
69
|
+
try {
|
|
70
|
+
events.push(JSON.parse(line) as NormalizedEvent);
|
|
71
|
+
} catch {
|
|
72
|
+
// skip malformed lines — never block readback on a single bad row
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return events;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function appendEvent(agent: string, session: string, ev: NormalizedEvent): Promise<void> {
|
|
79
|
+
await ensureDir(agent);
|
|
80
|
+
await appendFile(jsonlPath(agent, session), `${JSON.stringify(ev)}\n`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// In-process per-session serialization for read-merge-write meta updates.
|
|
84
|
+
// A plain get()+set() from two concurrent writers (turn-end engine write
|
|
85
|
+
// vs /sessions stats-cache write vs activity unread/seen mark) loses
|
|
86
|
+
// whichever read first — the second write spreads its stale snapshot over
|
|
87
|
+
// the first's field. Chaining each session's update() onto a per-key
|
|
88
|
+
// promise makes the read-merge-write atomic WITHIN the process (where all
|
|
89
|
+
// these writers live — the engine loop, /sessions handler and activity
|
|
90
|
+
// hub all run in the main server). Cross-process safety still rests on the
|
|
91
|
+
// atomic tmp+rename in set(); the practical clobber was always same-process
|
|
92
|
+
// (Juni-Audit 2026-06).
|
|
93
|
+
const metaUpdateChains = new Map<string, Promise<unknown>>();
|
|
94
|
+
|
|
95
|
+
export const sessionMetaStore: SessionMetaStore = {
|
|
96
|
+
async get(agent, session) {
|
|
97
|
+
try {
|
|
98
|
+
const raw = await readFile(metaPath(agent, session), 'utf8');
|
|
99
|
+
return JSON.parse(raw) as SessionMeta;
|
|
100
|
+
} catch (err) {
|
|
101
|
+
if (isEnoent(err)) return {};
|
|
102
|
+
throw err;
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
async set(agent, session, meta) {
|
|
106
|
+
await ensureDir(agent);
|
|
107
|
+
const path = metaPath(agent, session);
|
|
108
|
+
// Per-call unique tmp suffix so concurrent writers don't race the
|
|
109
|
+
// same `<path>.tmp` filename. process.pid alone isn't enough when
|
|
110
|
+
// multiple async paths run in the same process; add a counter +
|
|
111
|
+
// randomness as well.
|
|
112
|
+
const tmp = `${path}.tmp.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}`;
|
|
113
|
+
await writeFile(tmp, `${JSON.stringify(meta, null, 2)}\n`, 'utf8');
|
|
114
|
+
await rename(tmp, path);
|
|
115
|
+
},
|
|
116
|
+
async update(agent, session, merge) {
|
|
117
|
+
const k = `${agent}/${session}`;
|
|
118
|
+
const prev = metaUpdateChains.get(k) ?? Promise.resolve();
|
|
119
|
+
// Read-merge-write runs only after any in-flight update for this key
|
|
120
|
+
// settles, so two updates can't interleave their read and write.
|
|
121
|
+
const run = prev.then(async () => {
|
|
122
|
+
const current = await this.get(agent, session);
|
|
123
|
+
const next = merge(current);
|
|
124
|
+
await this.set(agent, session, next);
|
|
125
|
+
return next;
|
|
126
|
+
});
|
|
127
|
+
// Store a non-rejecting tail so a thrown update doesn't poison the
|
|
128
|
+
// next link in the chain.
|
|
129
|
+
const tail = run.then(
|
|
130
|
+
() => undefined,
|
|
131
|
+
() => undefined,
|
|
132
|
+
);
|
|
133
|
+
metaUpdateChains.set(k, tail);
|
|
134
|
+
try {
|
|
135
|
+
return (await run) as SessionMeta;
|
|
136
|
+
} finally {
|
|
137
|
+
// Drop the entry only if we're still the tail (no newer update
|
|
138
|
+
// queued behind us), so the map doesn't grow across short-lived
|
|
139
|
+
// sessions without discarding a pending chain.
|
|
140
|
+
if (metaUpdateChains.get(k) === tail) metaUpdateChains.delete(k);
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
function timestampForFilename(d: Date = new Date()): string {
|
|
146
|
+
const pad = (n: number) => String(n).padStart(2, '0');
|
|
147
|
+
return (
|
|
148
|
+
`${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}` +
|
|
149
|
+
`-${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function fileExists(path: string): Promise<boolean> {
|
|
154
|
+
try {
|
|
155
|
+
await access(path);
|
|
156
|
+
return true;
|
|
157
|
+
} catch {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function resolveSessionId(agent: string, ref: string): Promise<string | null> {
|
|
163
|
+
// Magic: main is always usable, even before its file exists
|
|
164
|
+
if (ref === 'main') return 'main';
|
|
165
|
+
|
|
166
|
+
// Exact id (YYYYMMDD-HHMMSS_<slug>): must point to an existing file
|
|
167
|
+
if (EXACT_ID_PATTERN.test(ref)) {
|
|
168
|
+
return (await fileExists(jsonlPath(agent, ref))) ? ref : null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// A file that is literally called this IS this session. Sessions
|
|
172
|
+
// created before the id format was enforced (and anything that once
|
|
173
|
+
// wrote a raw reference straight to disk) are listed under their own
|
|
174
|
+
// name, so they must be reachable under it too. Without this, a slug
|
|
175
|
+
// lookup below quietly answered with a DIFFERENT session that happened
|
|
176
|
+
// to end in the same word, and archiving hit that one instead — with
|
|
177
|
+
// HTTP 200 (2026-09-09 report). Ambiguity must never be resolved by
|
|
178
|
+
// silently picking the other object.
|
|
179
|
+
if (VALID_SLUG.test(ref) && (await fileExists(jsonlPath(agent, ref)))) return ref;
|
|
180
|
+
|
|
181
|
+
// Slug: find latest matching file
|
|
182
|
+
if (!VALID_SLUG.test(ref)) return null;
|
|
183
|
+
let entries: string[];
|
|
184
|
+
try {
|
|
185
|
+
entries = await readdir(sessionDir(agent));
|
|
186
|
+
} catch (err) {
|
|
187
|
+
if (isEnoent(err)) return null;
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
const matches = entries
|
|
191
|
+
.filter((f) => f.endsWith(`_${ref}.jsonl`) && EXACT_ID_PATTERN.test(f.replace(/\.jsonl$/, '')))
|
|
192
|
+
.sort()
|
|
193
|
+
.reverse();
|
|
194
|
+
if (matches.length === 0) return null;
|
|
195
|
+
return matches[0]!.replace(/\.jsonl$/, '');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A live session already carries this slug (finding F2, 2026-09-23). */
|
|
199
|
+
export class SessionSlugTakenError extends Error {
|
|
200
|
+
constructor(
|
|
201
|
+
readonly agent: string,
|
|
202
|
+
readonly slug: string,
|
|
203
|
+
readonly existingId: string,
|
|
204
|
+
) {
|
|
205
|
+
super(`session slug '${slug}' already exists for agent '${agent}' (id ${existingId}); archive or reset it, or pick another name`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The live (non-archived) session ids that carry `slug`, oldest first. */
|
|
210
|
+
export async function findLiveSessionsBySlug(agent: string, slug: string): Promise<string[]> {
|
|
211
|
+
let entries: string[];
|
|
212
|
+
try {
|
|
213
|
+
entries = await readdir(sessionDir(agent));
|
|
214
|
+
} catch (err) {
|
|
215
|
+
if (isEnoent(err)) return [];
|
|
216
|
+
throw err;
|
|
217
|
+
}
|
|
218
|
+
const re = new RegExp(`^\\d{8}-\\d{6}_${slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:-\\d+)?$`);
|
|
219
|
+
const out: string[] = [];
|
|
220
|
+
for (const f of entries.sort()) {
|
|
221
|
+
if (!f.endsWith('.jsonl')) continue;
|
|
222
|
+
const id = f.slice(0, -'.jsonl'.length);
|
|
223
|
+
if (!re.test(id)) continue;
|
|
224
|
+
const meta = await sessionMetaStore.get(agent, id);
|
|
225
|
+
if (metaIsArchived(id, meta)) continue;
|
|
226
|
+
if ((meta.slug ?? id.replace(/^\d{8}-\d{6}_/, '')) !== slug) continue;
|
|
227
|
+
out.push(id);
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function createSession(agent: string, slug: string): Promise<string> {
|
|
233
|
+
if (!VALID_SLUG.test(slug)) {
|
|
234
|
+
throw new Error(`invalid slug: ${JSON.stringify(slug)}; must match [A-Za-z0-9_-]+`);
|
|
235
|
+
}
|
|
236
|
+
if (slug === 'main') {
|
|
237
|
+
throw new Error('cannot create session with reserved slug "main"');
|
|
238
|
+
}
|
|
239
|
+
await ensureDir(agent);
|
|
240
|
+
// One live session per slug: `/session x` in one window and the sessions
|
|
241
|
+
// list would otherwise end up on two conversations of the same name.
|
|
242
|
+
const taken = await findLiveSessionsBySlug(agent, slug);
|
|
243
|
+
if (taken.length > 0) throw new SessionSlugTakenError(agent, slug, taken[taken.length - 1]!);
|
|
244
|
+
const baseId = `${timestampForFilename()}_${slug}`;
|
|
245
|
+
// Collision retry: when two callers create sessions with the same
|
|
246
|
+
// slug in the same second (parallel subagent spawns are the common
|
|
247
|
+
// case), the base id collides. Append `-N` until we find a free
|
|
248
|
+
// slot. Use the exclusive-create flag (wx) to atomically claim the
|
|
249
|
+
// jsonl filename — racing creators will get EEXIST and retry.
|
|
250
|
+
for (let attempt = 0; attempt < 64; attempt++) {
|
|
251
|
+
const id = attempt === 0 ? baseId : `${baseId}-${attempt}`;
|
|
252
|
+
try {
|
|
253
|
+
await writeFile(jsonlPath(agent, id), '', { flag: 'wx' });
|
|
254
|
+
await sessionMetaStore.set(agent, id, {
|
|
255
|
+
slug: attempt === 0 ? slug : `${slug}-${attempt}`,
|
|
256
|
+
createdAt: new Date().toISOString(),
|
|
257
|
+
});
|
|
258
|
+
return id;
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if ((err as NodeJS.ErrnoException).code === 'EEXIST') continue;
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
throw new Error(`createSession: could not find a free id starting from '${baseId}'`);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Reset a session: archive its current jsonl + meta to a timestamped name,
|
|
269
|
+
* and start the original session id fresh (empty jsonl, minimal meta).
|
|
270
|
+
*
|
|
271
|
+
* Use case: the magic `main` session can't be replaced — it always exists
|
|
272
|
+
* for an agent. Over months of chatting, the JSONL grows past anything
|
|
273
|
+
* useful and provider-side caches roll over expensively. /reset gives the
|
|
274
|
+
* user a clean main while preserving the old content as a resume-able
|
|
275
|
+
* archived session.
|
|
276
|
+
*
|
|
277
|
+
* Behavior:
|
|
278
|
+
* - If the source jsonl doesn't exist → nothing to do, returns null.
|
|
279
|
+
* - Archive name: `<UTC-timestamp>_<sourceId>-archive.jsonl|.meta.json`
|
|
280
|
+
* - The archived session can be resumed with `/session <archive-id>`
|
|
281
|
+
* just like any other session (its meta keeps the prior engine
|
|
282
|
+
* session-ids so claude/codex resume still works).
|
|
283
|
+
* - The freshly-empty original gets a meta with only `slug` (preserved
|
|
284
|
+
* from the source meta) so future turns start clean.
|
|
285
|
+
*/
|
|
286
|
+
export async function resetSession(
|
|
287
|
+
agent: string,
|
|
288
|
+
session: string,
|
|
289
|
+
): Promise<{ archivedId: string } | null> {
|
|
290
|
+
await ensureDir(agent);
|
|
291
|
+
const srcJsonl = jsonlPath(agent, session);
|
|
292
|
+
if (!(await fileExists(srcJsonl))) return null;
|
|
293
|
+
// No-op when there's nothing to archive. A prior reset leaves a fresh
|
|
294
|
+
// 0-byte jsonl behind (line ~270); without this guard a second reset
|
|
295
|
+
// would archive that empty file — and, in the same wall-clock second,
|
|
296
|
+
// rename it over the first archive and destroy the real history
|
|
297
|
+
// (Juni-Audit 2026-06). Empty source = nothing happened since reset.
|
|
298
|
+
try {
|
|
299
|
+
if ((await stat(srcJsonl)).size === 0) return null;
|
|
300
|
+
} catch {
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const ts = timestampForFilename();
|
|
305
|
+
// Collision-safe archive id. The filename timestamp has 1-second
|
|
306
|
+
// resolution and rename() clobbers silently, so two archives landing
|
|
307
|
+
// in the same second (rapid double-reset, double-submitted request)
|
|
308
|
+
// would otherwise overwrite each other and lose a full conversation.
|
|
309
|
+
// Probe for a free suffix. (Juni-Audit 2026-06.)
|
|
310
|
+
let archivedId = `${ts}_${sanitize(session, 'session')}-archive`;
|
|
311
|
+
for (let n = 2; await fileExists(jsonlPath(agent, archivedId)); n++) {
|
|
312
|
+
archivedId = `${ts}_${sanitize(session, 'session')}-archive-${n}`;
|
|
313
|
+
}
|
|
314
|
+
const dstJsonl = jsonlPath(agent, archivedId);
|
|
315
|
+
const dstMeta = metaPath(agent, archivedId);
|
|
316
|
+
|
|
317
|
+
await rename(srcJsonl, dstJsonl);
|
|
318
|
+
const srcMetaPath = metaPath(agent, session);
|
|
319
|
+
let preservedSlug: string | undefined;
|
|
320
|
+
let archivedMeta: SessionMeta | null = null;
|
|
321
|
+
if (await fileExists(srcMetaPath)) {
|
|
322
|
+
try {
|
|
323
|
+
const raw = await readFile(srcMetaPath, 'utf8');
|
|
324
|
+
const parsed = JSON.parse(raw) as SessionMeta;
|
|
325
|
+
preservedSlug = typeof parsed.slug === 'string' ? parsed.slug : undefined;
|
|
326
|
+
archivedMeta = parsed;
|
|
327
|
+
} catch {
|
|
328
|
+
// best-effort; don't block reset on a malformed meta
|
|
329
|
+
}
|
|
330
|
+
await rename(srcMetaPath, dstMeta);
|
|
331
|
+
}
|
|
332
|
+
// Flag the new archive copy explicitly so the Sessions tool surfaces it
|
|
333
|
+
// in the Archived tab without relying solely on the `-archive` id-suffix
|
|
334
|
+
// detection. Legacy archives created before this commit are still picked
|
|
335
|
+
// up via the suffix check in metaIsArchived().
|
|
336
|
+
if (archivedMeta) {
|
|
337
|
+
await sessionMetaStore.set(agent, archivedId, {
|
|
338
|
+
...archivedMeta,
|
|
339
|
+
archived: true,
|
|
340
|
+
archivedAt: new Date().toISOString(),
|
|
341
|
+
archiveReason: archivedMeta.archiveReason ?? 'auto-archive on /reset',
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Fresh meta for the resurrected session id. Slug preserved so
|
|
346
|
+
// listSessions still surfaces it sensibly.
|
|
347
|
+
const freshMeta: SessionMeta = {
|
|
348
|
+
...(preservedSlug ? { slug: preservedSlug } : {}),
|
|
349
|
+
createdAt: new Date().toISOString(),
|
|
350
|
+
resetFrom: archivedId,
|
|
351
|
+
};
|
|
352
|
+
await writeFile(metaPath(agent, session), JSON.stringify(freshMeta, null, 2), 'utf8');
|
|
353
|
+
|
|
354
|
+
// Touch an empty jsonl so the source session id stays resolvable.
|
|
355
|
+
// Without this, resolveSessionId() returns null for non-main ids
|
|
356
|
+
// (their fileExists() check fails), and any subsequent /chat/send
|
|
357
|
+
// 404s. `main` would still work via its magic path, but non-main
|
|
358
|
+
// sessions are equally allowed to /reset per the TUI hint.
|
|
359
|
+
await appendFile(jsonlPath(agent, session), '');
|
|
360
|
+
|
|
361
|
+
return { archivedId };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export interface SessionSummary {
|
|
365
|
+
id: string;
|
|
366
|
+
slug: string;
|
|
367
|
+
isMain: boolean;
|
|
368
|
+
createdAt: string | null;
|
|
369
|
+
lastActivity: string | null;
|
|
370
|
+
messageCount: number;
|
|
371
|
+
/** True if `meta.archived === true` or the id ends in `-archive`. */
|
|
372
|
+
isArchived: boolean;
|
|
373
|
+
/** Bytes on disk for the jsonl file (0 if file is missing — e.g. magic main). */
|
|
374
|
+
byteSize: number;
|
|
375
|
+
/** Last engine that touched this session (claude-cli / codex-cli / openai-compatible). */
|
|
376
|
+
engine?: string;
|
|
377
|
+
/** REM read-through marker (ms since epoch) — null if never. */
|
|
378
|
+
dreamCoverageTs: number | null;
|
|
379
|
+
/** Number of events with ts > dreamCoverageTs (i.e. not yet REM'd). */
|
|
380
|
+
dreamLagEvents: number;
|
|
381
|
+
/** Optional human note from the archive call. */
|
|
382
|
+
archiveReason?: string;
|
|
383
|
+
/** ISO timestamp when archived (manual archive or /reset). */
|
|
384
|
+
archivedAt?: string;
|
|
385
|
+
/** Currently-pinned project slug, if any (Phase Projects v1). Reflects
|
|
386
|
+
* the CURRENT state of session.meta.projectSlug — over a session's
|
|
387
|
+
* lifetime this can change as /projekt switches happen. Clients that
|
|
388
|
+
* want full per-session project history derive it from JSONL
|
|
389
|
+
* `project_switched` events. */
|
|
390
|
+
projectSlug?: string;
|
|
391
|
+
/** ISO timestamp of the latest unread-candidate event (A2A in,
|
|
392
|
+
* sentinel in, assistant final reply). Null if none yet. Compared
|
|
393
|
+
* against `seenAt` to compute the unread-badge state. */
|
|
394
|
+
unreadAt?: string | null;
|
|
395
|
+
/** ISO timestamp of when the user last opened this session in any
|
|
396
|
+
* client. Updated by POST /sessions/:agent/:session/seen. */
|
|
397
|
+
seenAt?: string | null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Returns true if the session is considered archived for filtering purposes:
|
|
401
|
+
* either the meta has `archived: true` (explicit user action OR /reset
|
|
402
|
+
* writing it forward), or the id ends in `-archive` (legacy /reset output
|
|
403
|
+
* before the explicit flag — backward-compat detect). */
|
|
404
|
+
function metaIsArchived(id: string, meta: SessionMeta): boolean {
|
|
405
|
+
return meta.archived === true || id.endsWith('-archive');
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
interface CachedStats {
|
|
409
|
+
jsonlMtime: number;
|
|
410
|
+
messageCount: number;
|
|
411
|
+
byteSize: number;
|
|
412
|
+
lastEventTs: number | null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Cached projection of jsonl stats. Reads the cache from meta and trusts it
|
|
416
|
+
* if the recorded jsonlMtime matches the current file mtime; otherwise
|
|
417
|
+
* recomputes and writes back. Active-chat sessions invalidate naturally
|
|
418
|
+
* every turn (mtime bumps) — that's OK, list calls are rare relative to
|
|
419
|
+
* turns. */
|
|
420
|
+
async function readSessionStats(agent: string, id: string, meta: SessionMeta): Promise<CachedStats> {
|
|
421
|
+
let jsonlMtime: number;
|
|
422
|
+
let byteSize: number;
|
|
423
|
+
try {
|
|
424
|
+
const s = await stat(jsonlPath(agent, id));
|
|
425
|
+
jsonlMtime = s.mtimeMs;
|
|
426
|
+
byteSize = s.size;
|
|
427
|
+
} catch (err) {
|
|
428
|
+
if (isEnoent(err)) {
|
|
429
|
+
// Magic main without a file yet — return zeros, no cache write.
|
|
430
|
+
return { jsonlMtime: 0, messageCount: 0, byteSize: 0, lastEventTs: null };
|
|
431
|
+
}
|
|
432
|
+
throw err;
|
|
433
|
+
}
|
|
434
|
+
const cache = meta.cache as CachedStats | undefined;
|
|
435
|
+
if (cache && typeof cache.jsonlMtime === 'number' && cache.jsonlMtime === jsonlMtime) {
|
|
436
|
+
// Hit — trust the cache for messageCount + lastEventTs, but always
|
|
437
|
+
// surface the live byteSize from stat (matches the cached value since
|
|
438
|
+
// mtime is the same, but cheaper to trust stat).
|
|
439
|
+
return {
|
|
440
|
+
jsonlMtime,
|
|
441
|
+
messageCount: cache.messageCount,
|
|
442
|
+
byteSize,
|
|
443
|
+
lastEventTs: cache.lastEventTs ?? null,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
// Miss — recompute by streaming the jsonl. getHistory parses every line;
|
|
447
|
+
// for very large sessions this is the slow path. Acceptable on cache-miss
|
|
448
|
+
// (which only happens after a real write).
|
|
449
|
+
const events = await getHistory(agent, id);
|
|
450
|
+
const lastEv = events[events.length - 1];
|
|
451
|
+
const messageCount = events.filter(
|
|
452
|
+
(e) => e.kind === 'user_message' || e.kind === 'assistant_message',
|
|
453
|
+
).length;
|
|
454
|
+
const lastEventTs = lastEv ? (lastEv.ts as number) : null;
|
|
455
|
+
const stats: CachedStats = { jsonlMtime, messageCount, byteSize, lastEventTs };
|
|
456
|
+
// Write back the cache via the atomic read-merge-write. getHistory above
|
|
457
|
+
// can take seconds on a big session; a plain set({ ...meta, cache }) would
|
|
458
|
+
// spread the turn-START `meta` snapshot and silently revert any
|
|
459
|
+
// sdkSessionId/projectSlug/unreadAt a turn-end write landed in between
|
|
460
|
+
// (Juni-Audit 2026-06). update() re-reads fresh under the per-session lock
|
|
461
|
+
// and touches only `cache`. Best-effort — cache is regenerable.
|
|
462
|
+
try {
|
|
463
|
+
await sessionMetaStore.update(agent, id, (current) => ({ ...current, cache: stats }));
|
|
464
|
+
} catch {
|
|
465
|
+
/* best-effort cache write */
|
|
466
|
+
}
|
|
467
|
+
return stats;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** Count events with ts > coverage. coverage=null means REM has never run,
|
|
471
|
+
* so all events are lag. */
|
|
472
|
+
function dreamLag(events: NormalizedEvent[], coverage: number | null): number {
|
|
473
|
+
if (coverage === null || coverage === 0) return events.length;
|
|
474
|
+
return events.filter((e) => (e.ts as number) > coverage).length;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
export interface ListSessionsOptions {
|
|
478
|
+
/** Include archived sessions in the result. Defaults to false — archived
|
|
479
|
+
* sessions should only surface in the dedicated Sessions tool, not in
|
|
480
|
+
* slash-command pickers or default chat-window UI. */
|
|
481
|
+
includeArchived?: boolean;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export async function listSessions(
|
|
485
|
+
agent: string,
|
|
486
|
+
options: ListSessionsOptions = {},
|
|
487
|
+
): Promise<SessionSummary[]> {
|
|
488
|
+
const includeArchived = options.includeArchived ?? false;
|
|
489
|
+
let entries: string[];
|
|
490
|
+
try {
|
|
491
|
+
entries = await readdir(sessionDir(agent));
|
|
492
|
+
} catch (err) {
|
|
493
|
+
if (!isEnoent(err)) throw err;
|
|
494
|
+
entries = [];
|
|
495
|
+
}
|
|
496
|
+
const ids = entries.filter((f) => f.endsWith('.jsonl')).map((f) => f.replace(/\.jsonl$/, ''));
|
|
497
|
+
|
|
498
|
+
const summaries: SessionSummary[] = [];
|
|
499
|
+
for (const id of ids) {
|
|
500
|
+
const isMain = id === 'main';
|
|
501
|
+
const slug = isMain ? 'main' : (id.match(/^\d{8}-\d{6}_(.+)$/)?.[1] ?? id);
|
|
502
|
+
const meta = await sessionMetaStore.get(agent, id);
|
|
503
|
+
const isArchived = metaIsArchived(id, meta);
|
|
504
|
+
if (isArchived && !includeArchived) continue;
|
|
505
|
+
const stats = await readSessionStats(agent, id, meta);
|
|
506
|
+
// Dream-lag needs the event list — only fetch it for cache-miss or for
|
|
507
|
+
// the live sessions where the coverage might lag the latest event. We
|
|
508
|
+
// already paid for getHistory in the cache-miss branch above; for hits
|
|
509
|
+
// we re-fetch only when there's a chance of lag (coverage < lastEventTs).
|
|
510
|
+
const coverage = typeof meta.dreamReadThroughTs === 'number' ? meta.dreamReadThroughTs : null;
|
|
511
|
+
let lag = 0;
|
|
512
|
+
if (stats.lastEventTs !== null) {
|
|
513
|
+
if (coverage === null) {
|
|
514
|
+
lag = stats.messageCount; // approximate: never-dreamed → all events lag
|
|
515
|
+
} else if (coverage < stats.lastEventTs) {
|
|
516
|
+
// Refetch events for an exact count — list-call performance is OK
|
|
517
|
+
// because this only fires for sessions with actual dream-lag.
|
|
518
|
+
const events = await getHistory(agent, id);
|
|
519
|
+
lag = dreamLag(events, coverage);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
summaries.push({
|
|
523
|
+
id,
|
|
524
|
+
slug,
|
|
525
|
+
isMain,
|
|
526
|
+
createdAt: typeof meta.createdAt === 'string' ? meta.createdAt : null,
|
|
527
|
+
lastActivity: stats.lastEventTs !== null ? new Date(stats.lastEventTs).toISOString() : null,
|
|
528
|
+
messageCount: stats.messageCount,
|
|
529
|
+
isArchived,
|
|
530
|
+
byteSize: stats.byteSize,
|
|
531
|
+
engine: typeof meta.engine === 'string' ? meta.engine : undefined,
|
|
532
|
+
dreamCoverageTs: coverage,
|
|
533
|
+
dreamLagEvents: lag,
|
|
534
|
+
archiveReason: typeof meta.archiveReason === 'string' ? meta.archiveReason : undefined,
|
|
535
|
+
archivedAt: typeof meta.archivedAt === 'string' ? meta.archivedAt : undefined,
|
|
536
|
+
projectSlug: typeof meta.projectSlug === 'string' ? meta.projectSlug : undefined,
|
|
537
|
+
unreadAt: typeof meta.unreadAt === 'string' ? meta.unreadAt : null,
|
|
538
|
+
seenAt: typeof meta.seenAt === 'string' ? meta.seenAt : null,
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Always surface main, even if its file doesn't exist yet (and it's
|
|
543
|
+
// never archived).
|
|
544
|
+
if (!summaries.some((s) => s.isMain)) {
|
|
545
|
+
summaries.push({
|
|
546
|
+
id: 'main',
|
|
547
|
+
slug: 'main',
|
|
548
|
+
isMain: true,
|
|
549
|
+
createdAt: null,
|
|
550
|
+
lastActivity: null,
|
|
551
|
+
messageCount: 0,
|
|
552
|
+
isArchived: false,
|
|
553
|
+
byteSize: 0,
|
|
554
|
+
dreamCoverageTs: null,
|
|
555
|
+
dreamLagEvents: 0,
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// Sort: main first, then newest activity first
|
|
560
|
+
summaries.sort((a, b) => {
|
|
561
|
+
if (a.isMain && !b.isMain) return -1;
|
|
562
|
+
if (b.isMain && !a.isMain) return 1;
|
|
563
|
+
return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
|
|
564
|
+
});
|
|
565
|
+
return summaries;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Mark a session archived via its meta. No file movement — the jsonl stays
|
|
569
|
+
* where it is, the meta gains `archived: true` + timestamp + optional reason.
|
|
570
|
+
* The `main` session is special: archiving main creates a `<ts>_main-archive`
|
|
571
|
+
* copy via resetSession instead (because main must always remain usable). */
|
|
572
|
+
export async function archiveSession(
|
|
573
|
+
agent: string,
|
|
574
|
+
session: string,
|
|
575
|
+
reason?: string,
|
|
576
|
+
): Promise<void> {
|
|
577
|
+
if (session === 'main') {
|
|
578
|
+
throw new Error(
|
|
579
|
+
"cannot archive the magic 'main' session directly — use /reset to spawn an archived copy",
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
await sessionMetaStore.update(agent, session, (current) => ({
|
|
583
|
+
...current,
|
|
584
|
+
archived: true,
|
|
585
|
+
archivedAt: new Date().toISOString(),
|
|
586
|
+
...(reason ? { archiveReason: reason } : {}),
|
|
587
|
+
}));
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Clear the archived flag. The id-suffix detection (`-archive`) still
|
|
591
|
+
* fires for legacy reset-archives, so unarchiving one of those is a no-op
|
|
592
|
+
* for visibility purposes — the suffix check overrides the meta flag.
|
|
593
|
+
* We still clear the meta flag for consistency. */
|
|
594
|
+
export async function unarchiveSession(agent: string, session: string): Promise<void> {
|
|
595
|
+
await sessionMetaStore.update(agent, session, (current) => {
|
|
596
|
+
const next = { ...current };
|
|
597
|
+
delete next.archived;
|
|
598
|
+
delete next.archivedAt;
|
|
599
|
+
delete next.archiveReason;
|
|
600
|
+
return next;
|
|
601
|
+
});
|
|
602
|
+
}
|