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,376 @@
|
|
|
1
|
+
// Per-session lock with a FIFO queue. Used by /chat/send
|
|
2
|
+
// and /chat/send-sync (and by extension agent_ask) so that two writers
|
|
3
|
+
// to the same agent's session never run concurrent turns — JSONL stays
|
|
4
|
+
// sane and the engine isn't double-driven.
|
|
5
|
+
//
|
|
6
|
+
// One queue, FIFO, no classes. The currently-running holder always
|
|
7
|
+
// finishes; we never preempt mid-turn — that would corrupt JSONL and
|
|
8
|
+
// confuse the engine.
|
|
9
|
+
//
|
|
10
|
+
// Turns still SAY where they come from:
|
|
11
|
+
// user — human-driven turn (POST /chat/send without from_agent)
|
|
12
|
+
// agent — A2A turn, sentinel, job, or a question asked in a voice call
|
|
13
|
+
// That label is diagnostics (/health, logs), not order. Until
|
|
14
|
+
// 2026-09-12 user turns jumped the queue; a voice call broke the rule,
|
|
15
|
+
// because a question asked out loud runs as an agent turn and so waited
|
|
16
|
+
// behind errands that a typed question would have overtaken.
|
|
17
|
+
//
|
|
18
|
+
// In-memory only — server restart drops queued waiters with abort errors.
|
|
19
|
+
// MVP scope; persistent queue is a FUTURE item if/when crash-recovery
|
|
20
|
+
// becomes a requirement (see A2A-design.md).
|
|
21
|
+
//
|
|
22
|
+
// Cancellation via AbortSignal: if the caller's signal fires while in
|
|
23
|
+
// the queue, we splice the entry out and reject with AbortError. If
|
|
24
|
+
// the entry was already running (lock held), the signal does nothing
|
|
25
|
+
// here — it's up to the caller's own code path to react.
|
|
26
|
+
|
|
27
|
+
import { logger } from './logger.ts';
|
|
28
|
+
|
|
29
|
+
type Priority = 'user' | 'agent';
|
|
30
|
+
|
|
31
|
+
/** Thrown to a waiter that was taken out of the queue by
|
|
32
|
+
* `dequeueSessionTurn` (DELETE /chat/queue/:turnId) — the turn never
|
|
33
|
+
* ran, and the caller must not treat it as a failure of the turn. */
|
|
34
|
+
export class DequeuedError extends Error {
|
|
35
|
+
constructor(readonly turnId: string) {
|
|
36
|
+
super(`turn ${turnId} was dequeued before it started`);
|
|
37
|
+
this.name = 'DequeuedError';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type DequeueOutcome =
|
|
42
|
+
| { status: 'removed'; remaining: Array<{ turnId: string; ahead: number }> }
|
|
43
|
+
| { status: 'running' }
|
|
44
|
+
| { status: 'unknown' };
|
|
45
|
+
|
|
46
|
+
interface Waiter {
|
|
47
|
+
priority: Priority;
|
|
48
|
+
enqueuedAt: number;
|
|
49
|
+
callId: string | undefined;
|
|
50
|
+
/** The work-ledger item this waiter runs for (Phase 2). Lets the
|
|
51
|
+
* ledger take any waiter back, not only a human one. */
|
|
52
|
+
workId: string | undefined;
|
|
53
|
+
/** Turn-lifecycle id — carried through the queue so /health's
|
|
54
|
+
* activeTurnId is populated for queued-then-run turns too, not only
|
|
55
|
+
* for immediately-granted ones (Juni-Audit 2026-06). */
|
|
56
|
+
turnId: string | undefined;
|
|
57
|
+
resolve: (release: () => void) => void;
|
|
58
|
+
reject: (err: Error) => void;
|
|
59
|
+
cancelled: boolean;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
class SessionLock {
|
|
63
|
+
private busy = false;
|
|
64
|
+
private queue: Waiter[] = [];
|
|
65
|
+
private activeSince: number | null = null;
|
|
66
|
+
private activePriority: Priority | null = null;
|
|
67
|
+
private activeCallId: string | undefined = undefined;
|
|
68
|
+
private activeTurnId: string | undefined = undefined;
|
|
69
|
+
private activeWorkId: string | undefined = undefined;
|
|
70
|
+
|
|
71
|
+
acquire(opts: {
|
|
72
|
+
priority: Priority;
|
|
73
|
+
callId?: string;
|
|
74
|
+
signal?: AbortSignal;
|
|
75
|
+
turnId?: string;
|
|
76
|
+
workId?: string;
|
|
77
|
+
/** Called synchronously AFTER the waiter has been pushed to the queue.
|
|
78
|
+
* `ahead` = number of turns this waiter must wait for, INCLUDING the
|
|
79
|
+
* currently-running one (1 = next in line). Used by /chat/send to
|
|
80
|
+
* emit a `turn_queued` SSE event so clients can render a queue
|
|
81
|
+
* indicator on the optimistic user-bubble. Not called when the lock
|
|
82
|
+
* is immediately granted. */
|
|
83
|
+
onQueued?: (ahead: number) => void;
|
|
84
|
+
}): Promise<() => void> {
|
|
85
|
+
if (!this.busy) {
|
|
86
|
+
this.busy = true;
|
|
87
|
+
this.activeSince = Date.now();
|
|
88
|
+
this.activePriority = opts.priority;
|
|
89
|
+
this.activeCallId = opts.callId;
|
|
90
|
+
this.activeTurnId = opts.turnId;
|
|
91
|
+
this.activeWorkId = opts.workId;
|
|
92
|
+
return Promise.resolve(() => this.release());
|
|
93
|
+
}
|
|
94
|
+
return new Promise<() => void>((resolve, reject) => {
|
|
95
|
+
const waiter: Waiter = {
|
|
96
|
+
priority: opts.priority,
|
|
97
|
+
enqueuedAt: Date.now(),
|
|
98
|
+
callId: opts.callId,
|
|
99
|
+
turnId: opts.turnId,
|
|
100
|
+
workId: opts.workId,
|
|
101
|
+
resolve: (release) => resolve(release),
|
|
102
|
+
reject: (err) => reject(err),
|
|
103
|
+
cancelled: false,
|
|
104
|
+
};
|
|
105
|
+
// First come, first served, whoever it is.
|
|
106
|
+
//
|
|
107
|
+
// Human turns used to jump ahead of agent turns. With a voice call
|
|
108
|
+
// in the picture that stopped being a clean rule: a spoken
|
|
109
|
+
// question runs as an agent turn, so the person at the microphone
|
|
110
|
+
// queued behind another agent's errand while the person typing did
|
|
111
|
+
// not — two humans, two answers (Rene, 2026-09-12: "alle haben die
|
|
112
|
+
// selbe prio wer als erster kommt mahlt zuerst das ist dann
|
|
113
|
+
// leichter zu warten").
|
|
114
|
+
//
|
|
115
|
+
// `priority` stays as a LABEL: /health shows who is waiting, and
|
|
116
|
+
// the logs say where a turn came from. It no longer decides order.
|
|
117
|
+
this.queue.push(waiter);
|
|
118
|
+
if (opts.onQueued) {
|
|
119
|
+
const idx = this.queue.indexOf(waiter);
|
|
120
|
+
// ahead = waiters in front of us (idx) + the currently-running turn (1)
|
|
121
|
+
opts.onQueued(idx + 1);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (opts.signal) {
|
|
125
|
+
if (opts.signal.aborted) {
|
|
126
|
+
waiter.cancelled = true;
|
|
127
|
+
const idx = this.queue.indexOf(waiter);
|
|
128
|
+
if (idx >= 0) this.queue.splice(idx, 1);
|
|
129
|
+
reject(new DOMException('aborted', 'AbortError'));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const onAbort = () => {
|
|
133
|
+
waiter.cancelled = true;
|
|
134
|
+
const idx = this.queue.indexOf(waiter);
|
|
135
|
+
if (idx >= 0) this.queue.splice(idx, 1);
|
|
136
|
+
reject(new DOMException('aborted', 'AbortError'));
|
|
137
|
+
};
|
|
138
|
+
opts.signal.addEventListener('abort', onAbort, { once: true });
|
|
139
|
+
}
|
|
140
|
+
}).then((release) => release);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Take a still-waiting USER turn out of the queue. Only user
|
|
144
|
+
* turns: A2A / sentinel waiters are not the human's to edit. The
|
|
145
|
+
* waiter's acquire() promise rejects with DequeuedError so the
|
|
146
|
+
* /chat/send continuation skips the turn. Atomic with respect to
|
|
147
|
+
* release(): both run on the event loop, and a waiter that release()
|
|
148
|
+
* already promoted is `activeTurnId`, not in `queue`. */
|
|
149
|
+
dequeue(turnId: string): DequeueOutcome {
|
|
150
|
+
const idx = this.queue.findIndex((w) => w.turnId === turnId && w.priority === 'user');
|
|
151
|
+
if (idx >= 0) {
|
|
152
|
+
const [waiter] = this.queue.splice(idx, 1);
|
|
153
|
+
waiter!.cancelled = true;
|
|
154
|
+
waiter!.reject(new DequeuedError(turnId));
|
|
155
|
+
return { status: 'removed', remaining: this.waitingUserTurns() };
|
|
156
|
+
}
|
|
157
|
+
if (this.activeTurnId === turnId) return { status: 'running' };
|
|
158
|
+
return { status: 'unknown' };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Take a waiter out by its work-ledger id — any priority. The
|
|
162
|
+
* ledger decides who may (a person: anything; an agent: its own),
|
|
163
|
+
* this only does it. Same atomicity as dequeue(). */
|
|
164
|
+
dequeueWork(workId: string): DequeueOutcome {
|
|
165
|
+
const idx = this.queue.findIndex((w) => w.workId === workId);
|
|
166
|
+
if (idx >= 0) {
|
|
167
|
+
const [waiter] = this.queue.splice(idx, 1);
|
|
168
|
+
waiter!.cancelled = true;
|
|
169
|
+
waiter!.reject(new DequeuedError(workId));
|
|
170
|
+
return { status: 'removed', remaining: this.waitingUserTurns() };
|
|
171
|
+
}
|
|
172
|
+
if (this.activeWorkId === workId) return { status: 'running' };
|
|
173
|
+
return { status: 'unknown' };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Every waiter in line, in order (Phase 2: the queue has names). */
|
|
177
|
+
waiting(): Array<{ workId?: string; turnId?: string; priority: Priority; enqueuedAt: number; position: number }> {
|
|
178
|
+
const out: Array<{ workId?: string; turnId?: string; priority: Priority; enqueuedAt: number; position: number }> = [];
|
|
179
|
+
let pos = 0;
|
|
180
|
+
for (const w of this.queue) {
|
|
181
|
+
if (w.cancelled) continue;
|
|
182
|
+
pos++;
|
|
183
|
+
out.push({ ...(w.workId ? { workId: w.workId } : {}), ...(w.turnId ? { turnId: w.turnId } : {}), priority: w.priority, enqueuedAt: w.enqueuedAt, position: pos });
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** User turns still waiting, with their current `ahead` (same
|
|
189
|
+
* semantics as onQueued: waiters in front + the running turn). */
|
|
190
|
+
waitingUserTurns(): Array<{ turnId: string; ahead: number }> {
|
|
191
|
+
const out: Array<{ turnId: string; ahead: number }> = [];
|
|
192
|
+
this.queue.forEach((w, idx) => {
|
|
193
|
+
if (w.priority === 'user' && w.turnId && !w.cancelled) out.push({ turnId: w.turnId, ahead: idx + 1 });
|
|
194
|
+
});
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private release(): void {
|
|
199
|
+
this.activeSince = null;
|
|
200
|
+
this.activePriority = null;
|
|
201
|
+
this.activeCallId = undefined;
|
|
202
|
+
this.activeTurnId = undefined;
|
|
203
|
+
this.activeWorkId = undefined;
|
|
204
|
+
while (this.queue.length > 0) {
|
|
205
|
+
const next = this.queue.shift()!;
|
|
206
|
+
if (next.cancelled) continue;
|
|
207
|
+
// Hand the lock to the next waiter; busy stays true so a fresh
|
|
208
|
+
// acquire() called between releases can't slip in front of them.
|
|
209
|
+
this.activeSince = Date.now();
|
|
210
|
+
this.activePriority = next.priority;
|
|
211
|
+
this.activeCallId = next.callId;
|
|
212
|
+
this.activeTurnId = next.turnId;
|
|
213
|
+
this.activeWorkId = next.workId;
|
|
214
|
+
next.resolve(() => this.release());
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
this.busy = false;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
status(): {
|
|
221
|
+
busy: boolean;
|
|
222
|
+
queueLength: number;
|
|
223
|
+
userWaiting: number;
|
|
224
|
+
agentWaiting: number;
|
|
225
|
+
activeSince: number | null;
|
|
226
|
+
activePriority: Priority | null;
|
|
227
|
+
activeCallId: string | undefined;
|
|
228
|
+
activeTurnId: string | undefined;
|
|
229
|
+
activeWorkId: string | undefined;
|
|
230
|
+
} {
|
|
231
|
+
return {
|
|
232
|
+
busy: this.busy,
|
|
233
|
+
queueLength: this.queue.length,
|
|
234
|
+
userWaiting: this.queue.filter((w) => w.priority === 'user').length,
|
|
235
|
+
agentWaiting: this.queue.filter((w) => w.priority === 'agent').length,
|
|
236
|
+
activeSince: this.activeSince,
|
|
237
|
+
activePriority: this.activePriority,
|
|
238
|
+
activeCallId: this.activeCallId,
|
|
239
|
+
activeTurnId: this.activeTurnId,
|
|
240
|
+
activeWorkId: this.activeWorkId,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const locks = new Map<string, SessionLock>();
|
|
246
|
+
|
|
247
|
+
function key(agent: string, session: string): string {
|
|
248
|
+
return `${agent}/${session}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Acquire the lock for `<agent>/<session>`. Resolves with a `release()`
|
|
253
|
+
* function — call it (typically in a finally block) when the turn is
|
|
254
|
+
* done. Forgetting to release deadlocks future turns on this session.
|
|
255
|
+
*
|
|
256
|
+
* Re-entry is NOT supported. If a tool handler running inside a turn
|
|
257
|
+
* tries to acquire the same session's lock, it'll deadlock — by design,
|
|
258
|
+
* because that's a sign of accidental recursion (e.g. agent_ask called
|
|
259
|
+
* with `agent: ctx.agent` + `session: ctx.session`). The agent_ask tool
|
|
260
|
+
* guards against that explicitly.
|
|
261
|
+
*/
|
|
262
|
+
export async function acquireSessionLock(
|
|
263
|
+
agent: string,
|
|
264
|
+
session: string,
|
|
265
|
+
opts: {
|
|
266
|
+
priority: Priority;
|
|
267
|
+
callId?: string;
|
|
268
|
+
signal?: AbortSignal;
|
|
269
|
+
turnId?: string;
|
|
270
|
+
workId?: string;
|
|
271
|
+
onQueued?: (ahead: number) => void;
|
|
272
|
+
},
|
|
273
|
+
): Promise<() => void> {
|
|
274
|
+
let lock = locks.get(key(agent, session));
|
|
275
|
+
if (!lock) {
|
|
276
|
+
lock = new SessionLock();
|
|
277
|
+
locks.set(key(agent, session), lock);
|
|
278
|
+
}
|
|
279
|
+
const before = lock.status();
|
|
280
|
+
if (before.busy) {
|
|
281
|
+
logger.info({
|
|
282
|
+
msg: 'session_queue.enqueued',
|
|
283
|
+
agent,
|
|
284
|
+
session,
|
|
285
|
+
priority: opts.priority,
|
|
286
|
+
...(opts.callId ? { call_id: opts.callId } : {}),
|
|
287
|
+
queue_before: before.queueLength,
|
|
288
|
+
user_waiting: before.userWaiting,
|
|
289
|
+
agent_waiting: before.agentWaiting,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
return lock.acquire(opts);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Take a queued user turn back out before it starts. `removed` means
|
|
297
|
+
* the waiter is gone and its acquire() rejected with DequeuedError;
|
|
298
|
+
* `running` means the lock already went to it (too late — the turn is
|
|
299
|
+
* in flight, /chat/abort is the tool for that); `unknown` means no such
|
|
300
|
+
* waiter on this session (finished, or never queued here).
|
|
301
|
+
*/
|
|
302
|
+
export function dequeueSessionTurn(agent: string, session: string, turnId: string): DequeueOutcome {
|
|
303
|
+
const lock = locks.get(key(agent, session));
|
|
304
|
+
if (!lock) return { status: 'unknown' };
|
|
305
|
+
const outcome = lock.dequeue(turnId);
|
|
306
|
+
logger.info({
|
|
307
|
+
msg: 'session_queue.dequeue',
|
|
308
|
+
agent,
|
|
309
|
+
session,
|
|
310
|
+
turnId,
|
|
311
|
+
status: outcome.status,
|
|
312
|
+
...(outcome.status === 'removed' ? { remaining: outcome.remaining.length } : {}),
|
|
313
|
+
});
|
|
314
|
+
return outcome;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function getSessionLockStatus(agent: string, session: string): ReturnType<SessionLock['status']> {
|
|
318
|
+
const lock = locks.get(key(agent, session));
|
|
319
|
+
return lock?.status() ?? {
|
|
320
|
+
busy: false,
|
|
321
|
+
queueLength: 0,
|
|
322
|
+
userWaiting: 0,
|
|
323
|
+
agentWaiting: 0,
|
|
324
|
+
activeSince: null,
|
|
325
|
+
activePriority: null,
|
|
326
|
+
activeCallId: undefined,
|
|
327
|
+
activeTurnId: undefined,
|
|
328
|
+
activeWorkId: undefined,
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Take any waiter back by its work-ledger id (see work-ledger.ts
|
|
333
|
+
* dequeueWork for who may). */
|
|
334
|
+
export function dequeueSessionWork(agent: string, session: string, workId: string): DequeueOutcome {
|
|
335
|
+
const lock = locks.get(key(agent, session));
|
|
336
|
+
if (!lock) return { status: 'unknown' };
|
|
337
|
+
const outcome = lock.dequeueWork(workId);
|
|
338
|
+
logger.info({ msg: 'session_queue.dequeue_work', agent, session, workId, status: outcome.status });
|
|
339
|
+
return outcome;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** The waiters of a session, in order, with their work ids. */
|
|
343
|
+
export function listSessionWaiters(agent: string, session: string): ReturnType<SessionLock['waiting']> {
|
|
344
|
+
const lock = locks.get(key(agent, session));
|
|
345
|
+
return lock ? lock.waiting() : [];
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Snapshot of every known session lock — busy or not — for diagnostic
|
|
350
|
+
* surfaces (`GET /health`). Returns one entry per (agent, session) that
|
|
351
|
+
* has ever held or queued a turn since server start. Cheap: in-memory
|
|
352
|
+
* map iteration.
|
|
353
|
+
*/
|
|
354
|
+
export function listAllSessionLockStates(): Array<{
|
|
355
|
+
agent: string;
|
|
356
|
+
session: string;
|
|
357
|
+
busy: boolean;
|
|
358
|
+
queueLength: number;
|
|
359
|
+
userWaiting: number;
|
|
360
|
+
agentWaiting: number;
|
|
361
|
+
activeSince: number | null;
|
|
362
|
+
activePriority: Priority | null;
|
|
363
|
+
activeCallId: string | undefined;
|
|
364
|
+
activeTurnId: string | undefined;
|
|
365
|
+
activeWorkId: string | undefined;
|
|
366
|
+
}> {
|
|
367
|
+
const out: ReturnType<typeof listAllSessionLockStates> = [];
|
|
368
|
+
for (const [k, lock] of locks.entries()) {
|
|
369
|
+
const slashIdx = k.indexOf('/');
|
|
370
|
+
if (slashIdx < 0) continue;
|
|
371
|
+
const agent = k.slice(0, slashIdx);
|
|
372
|
+
const session = k.slice(slashIdx + 1);
|
|
373
|
+
out.push({ agent, session, ...lock.status() });
|
|
374
|
+
}
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The working directory of a session.
|
|
2
|
+
//
|
|
3
|
+
// Until 2026-09-23 relative paths in the file tools resolved against
|
|
4
|
+
// the AGENT's workspace (agent.yaml `workspace.path`, else the server
|
|
5
|
+
// default) and exec's default cwd was the server process's cwd. A
|
|
6
|
+
// session pinned to a project that has a `workdir` (docs/projects.md)
|
|
7
|
+
// now works in that folder: file tools, exec, the builder's environment
|
|
8
|
+
// block and plan file. Without such a pin nothing changes.
|
|
9
|
+
//
|
|
10
|
+
// Stored on the session meta as `workdir` by focusProject (src/projects/
|
|
11
|
+
// focus.ts); read here by everyone who needs it. The meta file is small
|
|
12
|
+
// and read per call — a tool call already costs more than that.
|
|
13
|
+
|
|
14
|
+
import { isAbsolute } from 'node:path';
|
|
15
|
+
import type { Config } from '../config/types.ts';
|
|
16
|
+
import type { Persona } from '../persona/loader.ts';
|
|
17
|
+
import { sessionMetaStore } from '../storage/sessions.ts';
|
|
18
|
+
import { effectiveWorkspace } from './workspace.ts';
|
|
19
|
+
|
|
20
|
+
/** The pinned project's folder for this session, or null. */
|
|
21
|
+
export async function pinnedWorkdir(agent: string, session: string | undefined): Promise<string | null> {
|
|
22
|
+
if (!session) return null;
|
|
23
|
+
try {
|
|
24
|
+
const meta = (await sessionMetaStore.get(agent, session)) as Record<string, unknown>;
|
|
25
|
+
const w = meta.workdir;
|
|
26
|
+
return typeof w === 'string' && isAbsolute(w) ? w : null;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Pinned project folder, else the agent's workspace. */
|
|
33
|
+
export async function sessionWorkdir(
|
|
34
|
+
agent: string,
|
|
35
|
+
session: string | undefined,
|
|
36
|
+
persona: Persona,
|
|
37
|
+
config: Config,
|
|
38
|
+
): Promise<{ path: string; source: 'project' | 'workspace' }> {
|
|
39
|
+
const pinned = await pinnedWorkdir(agent, session);
|
|
40
|
+
if (pinned) return { path: pinned, source: 'project' };
|
|
41
|
+
return { path: effectiveWorkspace(persona, config), source: 'workspace' };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Same from session meta already in hand (no extra read). */
|
|
45
|
+
export function workdirFromMeta(meta: Record<string, unknown>, persona: Persona, config: Config): { path: string; source: 'project' | 'workspace' } {
|
|
46
|
+
const w = meta.workdir;
|
|
47
|
+
if (typeof w === 'string' && isAbsolute(w)) return { path: w, source: 'project' };
|
|
48
|
+
return { path: effectiveWorkspace(persona, config), source: 'workspace' };
|
|
49
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// HTTP/2-safe SSE helper. Hono's built-in streamSSE() unconditionally
|
|
2
|
+
// sets `Transfer-Encoding: chunked` and `Connection: keep-alive` —
|
|
3
|
+
// both forbidden in HTTP/2, so the @hono/node-server adapter throws
|
|
4
|
+
// `ERR_HTTP2_INVALID_CONNECTION_HEADERS` at writeHead time and the
|
|
5
|
+
// connection dies before any event reaches the client.
|
|
6
|
+
//
|
|
7
|
+
// This wrapper mirrors Hono's streamSSE() shape (so call-sites stay
|
|
8
|
+
// identical) but only sets the SSE-essential headers: Content-Type
|
|
9
|
+
// and Cache-Control. Headers that HTTP/2 forbids are left out;
|
|
10
|
+
// HTTP/1.1 clients still see correct semantics because the
|
|
11
|
+
// underlying Node response writer adds Transfer-Encoding: chunked
|
|
12
|
+
// automatically when no Content-Length is set.
|
|
13
|
+
|
|
14
|
+
import type { Context } from 'hono';
|
|
15
|
+
import { SSEStreamingApi } from 'hono/streaming';
|
|
16
|
+
|
|
17
|
+
interface SSEMessage {
|
|
18
|
+
event?: string;
|
|
19
|
+
data: string;
|
|
20
|
+
id?: string;
|
|
21
|
+
retry?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function streamSSEH2Safe(
|
|
25
|
+
c: Context,
|
|
26
|
+
cb: (stream: { writeSSE: (m: SSEMessage) => Promise<void>; close: () => void; closed: boolean; onAbort: (h: () => void) => void }) => Promise<void>,
|
|
27
|
+
): Response {
|
|
28
|
+
const { readable, writable } = new TransformStream();
|
|
29
|
+
const stream = new SSEStreamingApi(writable, readable);
|
|
30
|
+
|
|
31
|
+
// Match Hono's streamSSE flow but skip Transfer-Encoding /
|
|
32
|
+
// Connection. The adapter's chunked path is only triggered when
|
|
33
|
+
// Transfer-Encoding is set, so omitting it routes us through the
|
|
34
|
+
// streaming-without-chunked branch — which is HTTP/2-clean.
|
|
35
|
+
c.header('Content-Type', 'text/event-stream');
|
|
36
|
+
c.header('Cache-Control', 'no-cache');
|
|
37
|
+
c.header('X-Accel-Buffering', 'no');
|
|
38
|
+
|
|
39
|
+
// Run the user-supplied callback in the background — same pattern
|
|
40
|
+
// as Hono's streamSSE. Errors get logged, the stream closes either
|
|
41
|
+
// way so the client's EventSource sees a clean EOF.
|
|
42
|
+
void (async () => {
|
|
43
|
+
try {
|
|
44
|
+
await cb({
|
|
45
|
+
writeSSE: (m) => stream.writeSSE(m),
|
|
46
|
+
close: () => stream.close(),
|
|
47
|
+
get closed() {
|
|
48
|
+
return stream.closed;
|
|
49
|
+
},
|
|
50
|
+
onAbort: (h) => stream.onAbort(h),
|
|
51
|
+
});
|
|
52
|
+
} catch (err) {
|
|
53
|
+
// eslint-disable-next-line no-console
|
|
54
|
+
console.error('[somora-sse]', err);
|
|
55
|
+
} finally {
|
|
56
|
+
stream.close();
|
|
57
|
+
}
|
|
58
|
+
})();
|
|
59
|
+
|
|
60
|
+
return c.body(stream.responseReadable);
|
|
61
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Liveness for SSE streams and the transport under them.
|
|
2
|
+
//
|
|
3
|
+
// Report 2026-09-03 ("16 zombie streams after 25 minutes"): a browser
|
|
4
|
+
// on jittery WLAN drops off without a FIN/RST, the h2 session had
|
|
5
|
+
// `sessionTimeout: 0` (deliberately — long A2A turns must not be cut),
|
|
6
|
+
// no TCP keepalive was set (kernel default: first probe after 2 h),
|
|
7
|
+
// and a heartbeat write that never completes was only debug-logged.
|
|
8
|
+
// So /chat/stream subscribers of dead tabs stayed registered until
|
|
9
|
+
// the next restart, publish() kept writing into them, and the
|
|
10
|
+
// sse.connect/disconnect log could not tell who was still there.
|
|
11
|
+
//
|
|
12
|
+
// Three layers, mirroring what the tmux WebSockets already had:
|
|
13
|
+
// 1. h2 PING per session on an interval; no ACK within the timeout →
|
|
14
|
+
// the session is destroyed, every stream on it aborts, the normal
|
|
15
|
+
// disconnect path runs. Independent of socket buffers, so a
|
|
16
|
+
// silent peer is caught in ~interval + timeout.
|
|
17
|
+
// 2. TCP keepalive on every accepted socket (belt and braces, and the
|
|
18
|
+
// only signal for HTTP/1.1 clients that send nothing).
|
|
19
|
+
// 3. Heartbeat writes are watched: a write that rejects or does not
|
|
20
|
+
// resolve within `deadAfterMs` marks the stream dead → the handler
|
|
21
|
+
// tears it down and destroys the socket.
|
|
22
|
+
|
|
23
|
+
import type { Server as HttpServer } from 'node:http';
|
|
24
|
+
import type { Http2SecureServer, Http2Server, ServerHttp2Session } from 'node:http2';
|
|
25
|
+
import type { Socket } from 'node:net';
|
|
26
|
+
import type { Context } from 'hono';
|
|
27
|
+
import { logger } from './logger.ts';
|
|
28
|
+
|
|
29
|
+
export interface SseWriter {
|
|
30
|
+
writeSSE: (m: { event?: string; data: string }) => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface HeartbeatOptions {
|
|
34
|
+
intervalMs: number;
|
|
35
|
+
/** A heartbeat write still pending after this long marks the stream dead. */
|
|
36
|
+
deadAfterMs: number;
|
|
37
|
+
onDead: (reason: 'write_timeout' | 'write_error', detail?: string) => void;
|
|
38
|
+
/** Injectable clock/timers for tests. */
|
|
39
|
+
now?: () => number;
|
|
40
|
+
setInterval?: typeof setInterval;
|
|
41
|
+
clearInterval?: typeof clearInterval;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Start the heartbeat and watch each write. Returns a stop function.
|
|
46
|
+
* Only the FIRST dead verdict is reported; the caller stops the
|
|
47
|
+
* heartbeat from its teardown.
|
|
48
|
+
*/
|
|
49
|
+
export function startSseHeartbeat(stream: SseWriter, opts: HeartbeatOptions): () => void {
|
|
50
|
+
const now = opts.now ?? Date.now;
|
|
51
|
+
const setI = opts.setInterval ?? setInterval;
|
|
52
|
+
const clearI = opts.clearInterval ?? clearInterval;
|
|
53
|
+
let pendingSince: number | null = null;
|
|
54
|
+
let reported = false;
|
|
55
|
+
let stopped = false;
|
|
56
|
+
const dead = (reason: 'write_timeout' | 'write_error', detail?: string) => {
|
|
57
|
+
if (reported || stopped) return;
|
|
58
|
+
reported = true;
|
|
59
|
+
opts.onDead(reason, detail);
|
|
60
|
+
};
|
|
61
|
+
const timer = setI(() => {
|
|
62
|
+
if (stopped) return;
|
|
63
|
+
if (pendingSince !== null) {
|
|
64
|
+
if (now() - pendingSince >= opts.deadAfterMs) dead('write_timeout', `heartbeat write pending ${now() - pendingSince} ms`);
|
|
65
|
+
return; // don't stack writes on a stalled stream
|
|
66
|
+
}
|
|
67
|
+
pendingSince = now();
|
|
68
|
+
stream
|
|
69
|
+
.writeSSE({ event: 'heartbeat', data: String(now()) })
|
|
70
|
+
.then(() => {
|
|
71
|
+
pendingSince = null;
|
|
72
|
+
})
|
|
73
|
+
.catch((err) => {
|
|
74
|
+
pendingSince = null;
|
|
75
|
+
dead('write_error', String(err));
|
|
76
|
+
});
|
|
77
|
+
}, opts.intervalMs);
|
|
78
|
+
return () => {
|
|
79
|
+
stopped = true;
|
|
80
|
+
clearI(timer);
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Remote peer of the request behind a Hono context (node adapter). */
|
|
85
|
+
export function remoteOf(c: Context): { ip: string; port: number } | null {
|
|
86
|
+
const env = c.env as { incoming?: { socket?: Socket } } | undefined;
|
|
87
|
+
const s = env?.incoming?.socket;
|
|
88
|
+
if (!s || !s.remoteAddress) return null;
|
|
89
|
+
return { ip: s.remoteAddress.replace(/^::ffff:/, ''), port: s.remotePort ?? 0 };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Destroy the socket under a Hono request — used when a stream is
|
|
93
|
+
* declared dead so the kernel buffers stop absorbing writes. */
|
|
94
|
+
export function destroySocketOf(c: Context): void {
|
|
95
|
+
const env = c.env as { incoming?: { socket?: Socket } } | undefined;
|
|
96
|
+
try {
|
|
97
|
+
env?.incoming?.socket?.destroy();
|
|
98
|
+
} catch {
|
|
99
|
+
/* already gone */
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface TransportLivenessOptions {
|
|
104
|
+
keepAliveDelayMs: number;
|
|
105
|
+
h2PingIntervalMs: number;
|
|
106
|
+
h2PingTimeoutMs: number;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* TCP keepalive on every accepted socket; for an HTTP/2 server
|
|
111
|
+
* additionally a PING per session with a timeout. Returns a summary
|
|
112
|
+
* for the start log.
|
|
113
|
+
*/
|
|
114
|
+
export function installTransportLiveness(
|
|
115
|
+
server: HttpServer | Http2Server | Http2SecureServer,
|
|
116
|
+
opts: TransportLivenessOptions,
|
|
117
|
+
): { keepAlive: boolean; h2Ping: boolean } {
|
|
118
|
+
(server as HttpServer).on('connection', (socket: Socket) => {
|
|
119
|
+
try {
|
|
120
|
+
socket.setKeepAlive(true, opts.keepAliveDelayMs);
|
|
121
|
+
} catch {
|
|
122
|
+
/* not a TCP socket */
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
const isH2 = 'updateSettings' in server;
|
|
126
|
+
if (!isH2) return { keepAlive: true, h2Ping: false };
|
|
127
|
+
(server as Http2SecureServer).on('session', (session: ServerHttp2Session) => {
|
|
128
|
+
const remote = session.socket?.remoteAddress?.replace(/^::ffff:/, '') ?? '?';
|
|
129
|
+
let pending: ReturnType<typeof setTimeout> | null = null;
|
|
130
|
+
const timer = setInterval(() => {
|
|
131
|
+
if (session.destroyed || session.closed) return;
|
|
132
|
+
if (pending) return; // previous ping still outstanding — its timeout decides
|
|
133
|
+
pending = setTimeout(() => {
|
|
134
|
+
pending = null;
|
|
135
|
+
logger.info({ msg: 'transport.h2_session_dead', remote, hint: `no PING ack within ${opts.h2PingTimeoutMs} ms — destroying session, its SSE streams disconnect` });
|
|
136
|
+
session.destroy();
|
|
137
|
+
}, opts.h2PingTimeoutMs);
|
|
138
|
+
try {
|
|
139
|
+
const ok = session.ping((err) => {
|
|
140
|
+
if (pending) clearTimeout(pending);
|
|
141
|
+
pending = null;
|
|
142
|
+
if (err) logger.debug({ msg: 'transport.h2_ping_error', remote, err: String(err) });
|
|
143
|
+
});
|
|
144
|
+
if (!ok) {
|
|
145
|
+
// ping queue full — treat as pending until the timeout fires
|
|
146
|
+
}
|
|
147
|
+
} catch (err) {
|
|
148
|
+
if (pending) clearTimeout(pending);
|
|
149
|
+
pending = null;
|
|
150
|
+
logger.debug({ msg: 'transport.h2_ping_error', remote, err: String(err) });
|
|
151
|
+
}
|
|
152
|
+
}, opts.h2PingIntervalMs);
|
|
153
|
+
const cleanup = () => {
|
|
154
|
+
clearInterval(timer);
|
|
155
|
+
if (pending) clearTimeout(pending);
|
|
156
|
+
pending = null;
|
|
157
|
+
};
|
|
158
|
+
session.once('close', cleanup);
|
|
159
|
+
session.once('error', cleanup);
|
|
160
|
+
});
|
|
161
|
+
return { keepAlive: true, h2Ping: true };
|
|
162
|
+
}
|