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,113 @@
|
|
|
1
|
+
// Read/write the `tools:` section of an agent.yaml WITHOUT touching the
|
|
2
|
+
// rest of the file. agent.yaml is operator-edited and full of comments;
|
|
3
|
+
// a js-yaml round-trip would strip every one of them. So the update is
|
|
4
|
+
// a text splice: replace the existing top-level `tools:` block (from
|
|
5
|
+
// the `tools:` line up to the next top-level key / EOF) or append one.
|
|
6
|
+
//
|
|
7
|
+
// Consumed by PUT /agents/:name/tools (web UI Agents×Tools matrix —
|
|
8
|
+
// design private/mcp-hub-design.md §4.6). Reads go through the normal
|
|
9
|
+
// persona loader; this module is write-side only.
|
|
10
|
+
|
|
11
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import type { ToolGating } from '../tools/gating.ts';
|
|
15
|
+
|
|
16
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
17
|
+
const AGENTS_DIR = join(SOMORA_HOME, 'agents');
|
|
18
|
+
|
|
19
|
+
const PATTERN_SHAPE = /^[A-Za-z0-9_*:.-]+$/;
|
|
20
|
+
|
|
21
|
+
/** Validate one gating pattern (exact name, toolset:<tag>, trailing-*
|
|
22
|
+
* glob). Throws with a message suitable for a 400 body. */
|
|
23
|
+
export function assertValidPattern(p: string): void {
|
|
24
|
+
if (typeof p !== 'string' || p.length === 0 || p.length > 128 || !PATTERN_SHAPE.test(p)) {
|
|
25
|
+
throw new Error(`invalid tool pattern: ${JSON.stringify(p)}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Render the replacement block. Empty deny+allow = remove the section
|
|
30
|
+
* entirely (agent sees everything — same as before the UI touched it). */
|
|
31
|
+
export function renderToolsBlock(gating: ToolGating): string {
|
|
32
|
+
if (gating.deny.length === 0 && gating.allow.length === 0) return '';
|
|
33
|
+
const lines = ['tools:'];
|
|
34
|
+
if (gating.deny.length > 0) {
|
|
35
|
+
lines.push(' deny:');
|
|
36
|
+
for (const p of gating.deny) lines.push(` - ${JSON.stringify(p)}`);
|
|
37
|
+
}
|
|
38
|
+
if (gating.allow.length > 0) {
|
|
39
|
+
lines.push(' allow:');
|
|
40
|
+
for (const p of gating.allow) lines.push(` - ${JSON.stringify(p)}`);
|
|
41
|
+
}
|
|
42
|
+
return lines.join('\n') + '\n';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Splice a new `tools:` block into agent.yaml content. Handles the
|
|
47
|
+
* three cases: existing block replaced in place, no block → appended,
|
|
48
|
+
* empty gating → block removed. Top-level detection is column-0 keys —
|
|
49
|
+
* agent.yaml roots at column 0 (unlike the operator's config.yaml).
|
|
50
|
+
*/
|
|
51
|
+
export function spliceToolsBlock(yamlText: string, gating: ToolGating): string {
|
|
52
|
+
return spliceTopLevelBlock(
|
|
53
|
+
yamlText,
|
|
54
|
+
'tools',
|
|
55
|
+
renderToolsBlock(gating),
|
|
56
|
+
'# Per-agent tool visibility (managed via web UI — docs/mcp.md)',
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The generic splice behind spliceToolsBlock — `key` is the top-level
|
|
62
|
+
* YAML key to replace, `block` its full rendered replacement ('' =
|
|
63
|
+
* remove), `appendComment` the comment line written above a block that
|
|
64
|
+
* is being added for the first time. skill-gating-store.ts uses it for
|
|
65
|
+
* `skills:`; anything else that becomes web-managed can too.
|
|
66
|
+
*/
|
|
67
|
+
export function spliceTopLevelBlock(
|
|
68
|
+
yamlText: string,
|
|
69
|
+
key: string,
|
|
70
|
+
block: string,
|
|
71
|
+
appendComment: string,
|
|
72
|
+
): string {
|
|
73
|
+
const lines = yamlText.split('\n');
|
|
74
|
+
const keyRe = new RegExp(`^${key}:\\s*(#.*)?$`);
|
|
75
|
+
const start = lines.findIndex((l) => keyRe.test(l));
|
|
76
|
+
if (start === -1) {
|
|
77
|
+
if (block === '') return yamlText;
|
|
78
|
+
const sep = yamlText.length === 0 || yamlText.endsWith('\n') ? '' : '\n';
|
|
79
|
+
return `${yamlText}${sep}\n${appendComment}\n${block}`;
|
|
80
|
+
}
|
|
81
|
+
// Find the end of the block: the next column-0 line — a top-level
|
|
82
|
+
// key OR a top-level comment. Indented lines and blank lines inside
|
|
83
|
+
// the block belong to it; a `# …` at column 0 is the operator's note
|
|
84
|
+
// on whatever follows and must survive (the skills-store test caught
|
|
85
|
+
// the old key-only rule eating such a comment, 2026-08-31).
|
|
86
|
+
let end = lines.length;
|
|
87
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
88
|
+
const l = lines[i]!;
|
|
89
|
+
if (/^\S/.test(l)) {
|
|
90
|
+
end = i;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const before = lines.slice(0, start).join('\n');
|
|
95
|
+
const after = lines.slice(end).join('\n');
|
|
96
|
+
const mid = block === '' ? '' : block;
|
|
97
|
+
const sepBefore = before.length > 0 && !before.endsWith('\n') ? '\n' : '';
|
|
98
|
+
return `${before}${sepBefore}${mid}${after}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Full read-modify-write against the agent's on-disk agent.yaml.
|
|
102
|
+
* Missing file → created with just the tools block. */
|
|
103
|
+
export async function writeAgentToolGating(agent: string, gating: ToolGating): Promise<void> {
|
|
104
|
+
for (const p of [...gating.deny, ...gating.allow]) assertValidPattern(p);
|
|
105
|
+
const path = join(AGENTS_DIR, agent, 'agent.yaml');
|
|
106
|
+
let current = '';
|
|
107
|
+
try {
|
|
108
|
+
current = await readFile(path, 'utf8');
|
|
109
|
+
} catch {
|
|
110
|
+
// ENOENT — agent.yaml is optional; we create it.
|
|
111
|
+
}
|
|
112
|
+
await writeFile(path, spliceToolsBlock(current, gating), 'utf8');
|
|
113
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Session-focus helper. Single backend function shared by:
|
|
2
|
+
// - the project_focus Tool surface (agent-initiated focus changes)
|
|
3
|
+
// - the /projekt slash-command frontends (user-initiated focus changes
|
|
4
|
+
// in TUI and Web)
|
|
5
|
+
//
|
|
6
|
+
// Both call here so the side-effects (sessionMeta mutation + JSONL
|
|
7
|
+
// forensic event) happen identically regardless of who triggered the
|
|
8
|
+
// switch. The `via` argument is the only difference and survives in
|
|
9
|
+
// the JSONL event for later "who did this" forensics.
|
|
10
|
+
//
|
|
11
|
+
// Validation responsibility: this helper checks that the project file
|
|
12
|
+
// exists when slug != null. It does NOT cross-check the project's
|
|
13
|
+
// archived state — focusing an archived project is allowed (the
|
|
14
|
+
// session may legitimately want to revisit one); archive only affects
|
|
15
|
+
// project_list visibility.
|
|
16
|
+
|
|
17
|
+
import { appendEvent } from '../storage/sessions.ts';
|
|
18
|
+
import type { SessionMetaStore } from '../engine/types.ts';
|
|
19
|
+
import { logger } from '../server/logger.ts';
|
|
20
|
+
import { projectExists, readProject } from './store.ts';
|
|
21
|
+
import { loadPersona } from '../persona/loader.ts';
|
|
22
|
+
import { movePlanToWorkdir } from '../server/builder-session.ts';
|
|
23
|
+
import { loopbackFetch } from '../server/loopback-fetch.ts';
|
|
24
|
+
|
|
25
|
+
/** Is a turn running on the session? Asked over loopback so the answer is
|
|
26
|
+
* the same in the server and in the MCP child. Unreachable = not busy. */
|
|
27
|
+
async function sessionBusy(agent: string, session: string): Promise<boolean> {
|
|
28
|
+
const host = process.env.SOMORA_HOST || '127.0.0.1';
|
|
29
|
+
const port = process.env.SOMORA_PORT || '18737';
|
|
30
|
+
const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
|
|
31
|
+
try {
|
|
32
|
+
const res = await loopbackFetch(`${scheme}://${host}:${port}/agents/${encodeURIComponent(agent)}/sessions/${encodeURIComponent(session)}/work`);
|
|
33
|
+
if (!res.ok) return false;
|
|
34
|
+
const d = (await res.json()) as { busy?: boolean };
|
|
35
|
+
return d.busy === true;
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
import { homedir } from 'node:os';
|
|
41
|
+
import { isAbsolute, join, normalize } from 'node:path';
|
|
42
|
+
import { mkdir, stat } from 'node:fs/promises';
|
|
43
|
+
|
|
44
|
+
/** The project's working directory, expanded, or null when it has none
|
|
45
|
+
* or the value is not an absolute path after expansion. */
|
|
46
|
+
export async function projectWorkdir(slug: string): Promise<string | null> {
|
|
47
|
+
const project = await readProject(slug);
|
|
48
|
+
const raw = project?.workdir;
|
|
49
|
+
if (!raw) return null;
|
|
50
|
+
const expanded = raw === '~' ? homedir() : raw.startsWith('~/') ? join(homedir(), raw.slice(2)) : raw;
|
|
51
|
+
if (!isAbsolute(expanded)) {
|
|
52
|
+
logger.warn({ msg: 'project.workdir_not_absolute', slug, workdir: raw });
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
return normalize(expanded);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Create the project's working directory when it is missing (mkdir -p). */
|
|
59
|
+
export async function ensureWorkdirExists(workdir: string, slug: string): Promise<void> {
|
|
60
|
+
try {
|
|
61
|
+
const st = await stat(workdir);
|
|
62
|
+
if (!st.isDirectory()) logger.warn({ msg: 'project.workdir_not_a_directory', slug, workdir });
|
|
63
|
+
return;
|
|
64
|
+
} catch {
|
|
65
|
+
/* missing — create */
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
await mkdir(workdir, { recursive: true });
|
|
69
|
+
logger.info({ msg: 'project.workdir_created', slug, workdir });
|
|
70
|
+
} catch (err) {
|
|
71
|
+
logger.warn({ msg: 'project.workdir_create_failed', slug, workdir, err: err instanceof Error ? err.message : String(err) });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface FocusArgs {
|
|
76
|
+
agent: string;
|
|
77
|
+
session: string;
|
|
78
|
+
/** New project slug to pin, or null to clear focus. */
|
|
79
|
+
slug: string | null;
|
|
80
|
+
/** Provenance — `'tool'` when agent called project_focus, `'slash_command'`
|
|
81
|
+
* when user typed `/projekt`. Persisted in the JSONL event. */
|
|
82
|
+
via: 'tool' | 'slash_command';
|
|
83
|
+
metaStore: SessionMetaStore;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface FocusResult {
|
|
87
|
+
/** Slug that was active BEFORE this call (null if none). */
|
|
88
|
+
previousSlug: string | null;
|
|
89
|
+
/** Slug that is active AFTER this call (null if cleared). */
|
|
90
|
+
currentSlug: string | null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function focusProject(args: FocusArgs): Promise<FocusResult> {
|
|
94
|
+
const { agent, session, slug, via, metaStore } = args;
|
|
95
|
+
|
|
96
|
+
// Project must exist (unless we're clearing). Catches typos before
|
|
97
|
+
// we mutate session state.
|
|
98
|
+
if (slug !== null) {
|
|
99
|
+
const exists = await projectExists(slug);
|
|
100
|
+
if (!exists) {
|
|
101
|
+
throw new Error(`project '${slug}' does not exist`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const meta = await metaStore.get(agent, session);
|
|
106
|
+
const previousSlug = typeof meta.projectSlug === 'string' ? meta.projectSlug : null;
|
|
107
|
+
|
|
108
|
+
// A builder's write scope and working directory follow the pin. Taking
|
|
109
|
+
// the pin away or switching it while its turn runs moved the next write
|
|
110
|
+
// into the agent workspace (hardening test 2026-09-23) — so a running
|
|
111
|
+
// builder turn keeps the pin it has; a first pin is still allowed.
|
|
112
|
+
if (previousSlug !== null && slug !== previousSlug) {
|
|
113
|
+
const persona = await loadPersona(agent);
|
|
114
|
+
if (persona?.kind === 'builder' && (await sessionBusy(agent, session))) {
|
|
115
|
+
throw new Error(`the builder is working in project '${previousSlug}' right now — stop the turn before unpinning or switching the project`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Noop short-circuit: same slug requested as already active.
|
|
120
|
+
// Skip both the write AND the JSONL event so spam-clicking the same
|
|
121
|
+
// project doesn't pollute the session log.
|
|
122
|
+
if (previousSlug === slug) {
|
|
123
|
+
return { previousSlug, currentSlug: slug };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const ts = Date.now();
|
|
127
|
+
// Atomic read-merge-write: project_focus runs mid-turn (it's a tool),
|
|
128
|
+
// so it can race the /sessions stats-cache writer or an activity mark.
|
|
129
|
+
// A plain set() of the turn-start snapshot would revert their fields —
|
|
130
|
+
// and projectSlug itself was the field lost in the 2026-05-13 incident.
|
|
131
|
+
// update() re-reads fresh under the per-session lock (Juni-Audit 2026-06).
|
|
132
|
+
// A project with a `workdir` makes that folder the session's working
|
|
133
|
+
// directory (file tools, exec default cwd, builder environment);
|
|
134
|
+
// clearing the pin or pinning a project without one drops it.
|
|
135
|
+
const workdir = slug === null ? null : await projectWorkdir(slug);
|
|
136
|
+
// A project declared with a folder that is not there yet (a new
|
|
137
|
+
// repository the builder is about to start) gets the folder created
|
|
138
|
+
// now: every tool of the session runs there from this moment, and an
|
|
139
|
+
// exec whose cwd does not exist fails on every call.
|
|
140
|
+
if (workdir) await ensureWorkdirExists(workdir, slug!);
|
|
141
|
+
await metaStore.update(agent, session, (current) => {
|
|
142
|
+
const next = { ...current } as Record<string, unknown>;
|
|
143
|
+
if (slug === null) {
|
|
144
|
+
delete next.projectSlug;
|
|
145
|
+
delete next.projectLinkedAt;
|
|
146
|
+
delete next.workdir;
|
|
147
|
+
} else {
|
|
148
|
+
next.projectSlug = slug;
|
|
149
|
+
next.projectLinkedAt = new Date(ts).toISOString();
|
|
150
|
+
if (workdir) next.workdir = workdir;
|
|
151
|
+
else delete next.workdir;
|
|
152
|
+
}
|
|
153
|
+
return next as typeof current;
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// A builder's plan follows the pin (builder-session.ts movePlanToWorkdir).
|
|
157
|
+
if (workdir) {
|
|
158
|
+
const persona = await loadPersona(agent);
|
|
159
|
+
if (persona?.kind === 'builder') {
|
|
160
|
+
const moved = await movePlanToWorkdir(metaStore, agent, session, workdir);
|
|
161
|
+
if (moved) logger.info({ msg: 'builder.plan_path_followed_pin', agent, session, ...moved });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Forensic marker. The engine field is `'somora'` as a sentinel —
|
|
166
|
+
// not engine-emitted. See NormalizedEvent.project_switched.
|
|
167
|
+
await appendEvent(agent, session, {
|
|
168
|
+
kind: 'project_switched',
|
|
169
|
+
ts,
|
|
170
|
+
engine: 'somora',
|
|
171
|
+
from: previousSlug,
|
|
172
|
+
to: slug,
|
|
173
|
+
via,
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
logger.info({
|
|
177
|
+
msg: 'project.focus_changed',
|
|
178
|
+
agent,
|
|
179
|
+
session,
|
|
180
|
+
from: previousSlug,
|
|
181
|
+
to: slug,
|
|
182
|
+
via,
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
return { previousSlug, currentSlug: slug };
|
|
186
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Renders a project as a compact Markdown block for injection into the
|
|
2
|
+
// system-prompt tail. Lives in the STABLE portion of the prompt (after
|
|
3
|
+
// skillsBlock, before per-turn ephemeralContext) so cache holds for
|
|
4
|
+
// every turn within the same session — only an explicit `/projekt`
|
|
5
|
+
// switch invalidates it, which is intentional.
|
|
6
|
+
//
|
|
7
|
+
// Design goals:
|
|
8
|
+
// - kept short (target ≤ 800 tokens at typical 3–8 path counts)
|
|
9
|
+
// - human-readable so the agent has no parsing burden
|
|
10
|
+
// - scheme-tag (`[local]` / `[url]` / `[resource]`) per path so the
|
|
11
|
+
// agent knows which tool family to use without further inference
|
|
12
|
+
// - basename fallback for missing labels — raw paths read like noise
|
|
13
|
+
// ("Setup.md" beats "~/Documents/somora-vault/Privat/Heimkino/Setup.md")
|
|
14
|
+
//
|
|
15
|
+
// What we DON'T include here:
|
|
16
|
+
// - actual file contents (the agent uses its existing tools to read
|
|
17
|
+
// on demand — see Variante A of the design discussion)
|
|
18
|
+
// - paths to skills, memory, wiki — those go through their own injection
|
|
19
|
+
// - timestamps beyond `expires` (clutter; agent rarely needs created/updated)
|
|
20
|
+
|
|
21
|
+
import { basename } from 'node:path';
|
|
22
|
+
import { inferPathType } from './scheme.ts';
|
|
23
|
+
import type { ProjectFrontmatter } from './types.ts';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Render a project as the system-prompt project-block. Returns the
|
|
27
|
+
* empty string if `project` is null/undefined so callers can do a
|
|
28
|
+
* blanket `prompt + renderProjectBlock(p)` without conditional logic.
|
|
29
|
+
*/
|
|
30
|
+
export function renderProjectBlock(project: ProjectFrontmatter | null | undefined): string {
|
|
31
|
+
if (!project) return '';
|
|
32
|
+
|
|
33
|
+
const lines: string[] = [];
|
|
34
|
+
// Section delimiter matches the existing `---` separators in
|
|
35
|
+
// systemPromptForTurn (selfPointer + persona + skills).
|
|
36
|
+
lines.push('\n\n---\n');
|
|
37
|
+
lines.push(`## Active Project: ${project.name}`);
|
|
38
|
+
lines.push('');
|
|
39
|
+
lines.push(`**Entity:** ${project.entity}`);
|
|
40
|
+
if (project.description) {
|
|
41
|
+
lines.push(`**Description:** ${project.description}`);
|
|
42
|
+
}
|
|
43
|
+
if (project.tags.length > 0) {
|
|
44
|
+
lines.push(`**Tags:** ${project.tags.join(', ')}`);
|
|
45
|
+
}
|
|
46
|
+
if (project.expires) {
|
|
47
|
+
lines.push(`**Expires:** ${project.expires}`);
|
|
48
|
+
}
|
|
49
|
+
if (project.archived) {
|
|
50
|
+
// Should be rare but possible — focused project was archived after
|
|
51
|
+
// pin. Flag it so the agent knows the context is stale.
|
|
52
|
+
lines.push(`**⚠ Archived:** ${project.archiveReason ?? '(no reason given)'}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (project.paths.length > 0) {
|
|
56
|
+
lines.push('');
|
|
57
|
+
lines.push('**Pointers:**');
|
|
58
|
+
for (const p of project.paths) {
|
|
59
|
+
const inferred = inferPathType(p.ref);
|
|
60
|
+
const typeTag = inferred ? inferred.type : 'unknown';
|
|
61
|
+
const label = p.label ?? deriveLabel(p.ref, typeTag);
|
|
62
|
+
lines.push(`- \`[${typeTag}]\` ${p.ref} — ${label}`);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
lines.push('');
|
|
66
|
+
lines.push('*(no pointers configured yet)*');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
lines.push('');
|
|
70
|
+
lines.push(
|
|
71
|
+
'When the user asks about this project, treat the pointers above as the canonical ' +
|
|
72
|
+
'list of relevant resources. Use your standard tools (file_read for `[local]`, ' +
|
|
73
|
+
'web_fetch / browser tools for `[url]`, resource tools for `[resource]`) to access ' +
|
|
74
|
+
'them on demand — do not assume their contents from memory.',
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
return lines.join('\n');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Best-effort fallback label when `path.label` was omitted by the user.
|
|
81
|
+
* Returns the basename for local paths, the host for URLs, and the
|
|
82
|
+
* remote-path basename for resources. Plain `path` if nothing better
|
|
83
|
+
* can be derived. */
|
|
84
|
+
function deriveLabel(ref: string, type: string): string {
|
|
85
|
+
try {
|
|
86
|
+
if (type === 'url') {
|
|
87
|
+
const u = new URL(ref);
|
|
88
|
+
return u.hostname || ref;
|
|
89
|
+
}
|
|
90
|
+
if (type === 'local') {
|
|
91
|
+
const b = basename(ref.replace(/\/$/, ''));
|
|
92
|
+
return b || ref;
|
|
93
|
+
}
|
|
94
|
+
if (type === 'resource') {
|
|
95
|
+
// resource refs are `<slug>:/path/...`. Take the remote basename.
|
|
96
|
+
const m = ref.match(/^[a-z0-9_-]+:\/(.*)$/i);
|
|
97
|
+
if (m && m[1]) {
|
|
98
|
+
const b = basename(m[1].replace(/\/$/, ''));
|
|
99
|
+
if (b) return b;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
/* fall through */
|
|
104
|
+
}
|
|
105
|
+
return ref;
|
|
106
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Path-scheme inference for project pointer entries.
|
|
2
|
+
//
|
|
3
|
+
// Project files store paths as `{ref, label?}` — no `type` field. The
|
|
4
|
+
// type is inferred from the `ref` string itself at the moment we need
|
|
5
|
+
// it (validation at write-time, rendering at prompt-build-time). Three
|
|
6
|
+
// schemes are recognized:
|
|
7
|
+
//
|
|
8
|
+
// url → starts with a recognized URI scheme (https:// gdrive://
|
|
9
|
+
// etc.). No further validation — URLs can point anywhere.
|
|
10
|
+
// local → starts with `/` or `~` (absolute or home-relative
|
|
11
|
+
// local-filesystem path on the somora host). Existence is
|
|
12
|
+
// NOT checked — paths may legitimately point at things
|
|
13
|
+
// that don't exist yet.
|
|
14
|
+
// resource → matches `<word>:/path` where `<word>` is the slug of an
|
|
15
|
+
// entry in `config.resources`. Cross-checked at write
|
|
16
|
+
// time; unknown prefix → reject with helpful list.
|
|
17
|
+
//
|
|
18
|
+
// Anything else fails inference with a clear "doesn't look like url,
|
|
19
|
+
// absolute local, or resource:/" error.
|
|
20
|
+
//
|
|
21
|
+
// Why no stored `type` field: a single `add_path` tool argument shape
|
|
22
|
+
// (`ref` + optional `label`) covers all three schemes uniformly. Adding
|
|
23
|
+
// a new scheme is a parser change here, not a frontmatter migration.
|
|
24
|
+
// Tradeoff acknowledged: a literal file named `mac-studio.md` with no
|
|
25
|
+
// colon-slash never collides; a literal local path like
|
|
26
|
+
// `/home/foo/weird:/file` is a theoretical edge case we're willing to
|
|
27
|
+
// defer until it bites someone.
|
|
28
|
+
|
|
29
|
+
import type { Config } from '../config/types.ts';
|
|
30
|
+
|
|
31
|
+
export type PathType = 'url' | 'local' | 'resource';
|
|
32
|
+
|
|
33
|
+
/** Match any RFC-3986-style scheme followed by `://`. Covers https,
|
|
34
|
+
* http, ftp, gdrive, s3, file, gs, ssh, anything someone invents. */
|
|
35
|
+
const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
36
|
+
|
|
37
|
+
/** Match `<word>:/path` where the prefix segment looks like a resource
|
|
38
|
+
* slug. The actual existence check against config.resources happens
|
|
39
|
+
* in `validatePathRef` — this regex just identifies candidates. */
|
|
40
|
+
const RESOURCE_PREFIX_RE = /^([a-z0-9_-]+):\/(.*)$/i;
|
|
41
|
+
|
|
42
|
+
export interface InferredPath {
|
|
43
|
+
type: PathType;
|
|
44
|
+
/** For `resource` paths: the resource slug (the `<word>` part). */
|
|
45
|
+
resource?: string;
|
|
46
|
+
/** For `resource` paths: the path component after `<word>:/`. */
|
|
47
|
+
remotePath?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Infer the type of a `ref` without checking config. Returns null if
|
|
52
|
+
* the ref doesn't match any known scheme. Used at RENDER time where
|
|
53
|
+
* config is available but we don't want to re-validate (writes already
|
|
54
|
+
* gated through `validatePathRef`).
|
|
55
|
+
*/
|
|
56
|
+
export function inferPathType(ref: string): InferredPath | null {
|
|
57
|
+
if (URL_SCHEME_RE.test(ref)) {
|
|
58
|
+
return { type: 'url' };
|
|
59
|
+
}
|
|
60
|
+
if (ref.startsWith('/') || ref.startsWith('~')) {
|
|
61
|
+
return { type: 'local' };
|
|
62
|
+
}
|
|
63
|
+
const m = ref.match(RESOURCE_PREFIX_RE);
|
|
64
|
+
if (m && m[1] && m[2] !== undefined) {
|
|
65
|
+
return { type: 'resource', resource: m[1], remotePath: m[2] };
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ValidationResult {
|
|
71
|
+
ok: true;
|
|
72
|
+
inferred: InferredPath;
|
|
73
|
+
}
|
|
74
|
+
export interface ValidationError {
|
|
75
|
+
ok: false;
|
|
76
|
+
error: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Validate a `ref` against the current config — used at WRITE time
|
|
81
|
+
* (project_create paths[], project_update add_path). Verifies the
|
|
82
|
+
* scheme is recognized AND for `resource:/...` refs that the resource
|
|
83
|
+
* is actually configured. Returns a structured result so callers can
|
|
84
|
+
* compose multi-op error messages without parsing strings.
|
|
85
|
+
*/
|
|
86
|
+
export function validatePathRef(ref: string, config: Config): ValidationResult | ValidationError {
|
|
87
|
+
const inferred = inferPathType(ref);
|
|
88
|
+
if (!inferred) {
|
|
89
|
+
return {
|
|
90
|
+
ok: false,
|
|
91
|
+
error:
|
|
92
|
+
`path '${ref}' doesn't look like a URL (https://...), absolute local path (/... or ~/...) or resource (<resource-slug>:/path)`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (inferred.type === 'resource') {
|
|
96
|
+
const slug = inferred.resource!;
|
|
97
|
+
const known = Object.keys(config.resources ?? {});
|
|
98
|
+
if (!known.includes(slug)) {
|
|
99
|
+
const available = known.length > 0 ? known.join(', ') : '(no resources configured)';
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
error: `unknown resource '${slug}' in path '${ref}' — available: ${available}`,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { ok: true, inferred };
|
|
107
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Project file CRUD. Storage layout:
|
|
2
|
+
//
|
|
3
|
+
// ~/.somora/projects/<slug>.md
|
|
4
|
+
//
|
|
5
|
+
// One Markdown+YAML-frontmatter file per project. Body is intentionally
|
|
6
|
+
// empty in v1 — the project IS its frontmatter. Free-form notes that
|
|
7
|
+
// "belong to" a project live in separate .md files referenced via
|
|
8
|
+
// `paths`, not inside the project file itself.
|
|
9
|
+
//
|
|
10
|
+
// Writes are atomic via tmp+rename (same pattern as sessionMetaStore).
|
|
11
|
+
// All validation against config (entity vs. config.projects.entities,
|
|
12
|
+
// resource refs vs. config.resources) is done by callers in the tools
|
|
13
|
+
// layer — this module trusts its inputs schema-wise and just does I/O.
|
|
14
|
+
|
|
15
|
+
import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { homedir } from 'node:os';
|
|
17
|
+
import { dirname, join } from 'node:path';
|
|
18
|
+
import matter from 'gray-matter';
|
|
19
|
+
import { PROJECT_SLUG_RE, ProjectFrontmatterSchema, type ProjectFrontmatter } from './types.ts';
|
|
20
|
+
|
|
21
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
22
|
+
const PROJECTS_DIR = join(SOMORA_HOME, 'projects');
|
|
23
|
+
|
|
24
|
+
function projectPath(slug: string): string {
|
|
25
|
+
if (!PROJECT_SLUG_RE.test(slug)) {
|
|
26
|
+
throw new Error(`invalid project slug '${slug}' — must match ${PROJECT_SLUG_RE.source}`);
|
|
27
|
+
}
|
|
28
|
+
return join(PROJECTS_DIR, `${slug}.md`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isEnoent(err: unknown): boolean {
|
|
32
|
+
return typeof err === 'object' && err !== null && (err as NodeJS.ErrnoException).code === 'ENOENT';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function ensureDir(): Promise<void> {
|
|
36
|
+
await mkdir(PROJECTS_DIR, { recursive: true });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Read and parse a project file. Returns null when the file doesn't
|
|
41
|
+
* exist (caller decides 404 vs. create-new). Throws on schema-invalid
|
|
42
|
+
* content so an editor-corrupted file doesn't silently pass through.
|
|
43
|
+
*/
|
|
44
|
+
export async function readProject(slug: string): Promise<ProjectFrontmatter | null> {
|
|
45
|
+
let raw: string;
|
|
46
|
+
try {
|
|
47
|
+
raw = await readFile(projectPath(slug), 'utf8');
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (isEnoent(err)) return null;
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
const parsed = matter(raw);
|
|
53
|
+
const data = parsed.data ?? {};
|
|
54
|
+
// Slug is mirrored in the frontmatter for round-trip robustness; if a
|
|
55
|
+
// user renamed the file by hand and the inner slug now disagrees,
|
|
56
|
+
// trust the FILENAME and overwrite the frontmatter slug at next write.
|
|
57
|
+
// For read, return what's on disk — the caller can decide.
|
|
58
|
+
const result = ProjectFrontmatterSchema.safeParse({ ...data, slug });
|
|
59
|
+
if (!result.success) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`project '${slug}' has invalid frontmatter: ${result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return result.data;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function projectExists(slug: string): Promise<boolean> {
|
|
68
|
+
try {
|
|
69
|
+
await stat(projectPath(slug));
|
|
70
|
+
return true;
|
|
71
|
+
} catch (err) {
|
|
72
|
+
if (isEnoent(err)) return false;
|
|
73
|
+
throw err;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Atomic write — tmp+rename pattern. Adds a unique tmp suffix so
|
|
79
|
+
* concurrent writers (rare but possible: multi-agent flows) don't race
|
|
80
|
+
* the same `<path>.tmp` filename. Same precedent as sessionMetaStore.
|
|
81
|
+
*/
|
|
82
|
+
export async function writeProject(project: ProjectFrontmatter): Promise<void> {
|
|
83
|
+
await ensureDir();
|
|
84
|
+
const path = projectPath(project.slug);
|
|
85
|
+
// gray-matter.stringify expects (body, data). Empty body for v1.
|
|
86
|
+
const content = matter.stringify('', project);
|
|
87
|
+
const tmp = `${path}.tmp.${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}`;
|
|
88
|
+
await mkdir(dirname(path), { recursive: true });
|
|
89
|
+
await writeFile(tmp, content, 'utf8');
|
|
90
|
+
await rename(tmp, path);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* List all projects on disk. Returns parsed frontmatters; files that
|
|
95
|
+
* fail schema validation are SKIPPED (logged in caller's responsibility
|
|
96
|
+
* — store stays silent so list() never throws on one broken file).
|
|
97
|
+
* Sorted by `updated` desc.
|
|
98
|
+
*/
|
|
99
|
+
export async function listProjects(): Promise<ProjectFrontmatter[]> {
|
|
100
|
+
let entries: string[];
|
|
101
|
+
try {
|
|
102
|
+
entries = await readdir(PROJECTS_DIR);
|
|
103
|
+
} catch (err) {
|
|
104
|
+
if (isEnoent(err)) return [];
|
|
105
|
+
throw err;
|
|
106
|
+
}
|
|
107
|
+
const slugs = entries
|
|
108
|
+
.filter((f) => f.endsWith('.md'))
|
|
109
|
+
.map((f) => f.replace(/\.md$/, ''))
|
|
110
|
+
.filter((s) => PROJECT_SLUG_RE.test(s));
|
|
111
|
+
const projects: ProjectFrontmatter[] = [];
|
|
112
|
+
for (const slug of slugs) {
|
|
113
|
+
try {
|
|
114
|
+
const p = await readProject(slug);
|
|
115
|
+
if (p) projects.push(p);
|
|
116
|
+
} catch {
|
|
117
|
+
// skip broken files silently — list() shouldn't fail entirely on
|
|
118
|
+
// one corrupt frontmatter
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
projects.sort((a, b) => b.updated.localeCompare(a.updated));
|
|
122
|
+
return projects;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Hard-delete a project file. NOT exposed via tools in v1 — soft-delete
|
|
127
|
+
* (archive flag) is the user-facing path. This is here for completeness
|
|
128
|
+
* + future admin commands. Manual `rm ~/.somora/projects/<slug>.md` is
|
|
129
|
+
* the v1 escape hatch.
|
|
130
|
+
*/
|
|
131
|
+
export async function deleteProjectFile(slug: string): Promise<boolean> {
|
|
132
|
+
try {
|
|
133
|
+
await unlink(projectPath(slug));
|
|
134
|
+
return true;
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (isEnoent(err)) return false;
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Helper exposed for tests / smoke scripts that need the concrete path. */
|
|
142
|
+
export function projectFilePath(slug: string): string {
|
|
143
|
+
return projectPath(slug);
|
|
144
|
+
}
|