diff --git a/.env.example b/.env.example
index 542cac06f..d2c3de2e0 100644
--- a/.env.example
+++ b/.env.example
@@ -11,6 +11,9 @@ MEMMY_GA4_MEASUREMENT_ID=
MEMMY_LEGAL_CN_BASE_URL=https://memmy.cn
MEMMY_LEGAL_INTL_BASE_URL=https://memmy.bot
+# How often the owner's Memmy organizes new project memory into work items (ms, default 5 minutes).
+# MEMMY_COLLAB_ORGANIZE_INTERVAL_MS=300000
+
# Exact hosts available to sandboxed command plugins. Keep this aligned with
# the first-party literature-review plugin's declared academic providers.
MEMMY_COMMAND_PLUGIN_NETWORK_ALLOWLIST=export.arxiv.org,arxiv.org,eutils.ncbi.nlm.nih.gov,pmc.ncbi.nlm.nih.gov,api.openalex.org,api.crossref.org
diff --git a/.github/release-notes/v1.2.7.md b/.github/release-notes/v1.2.7.md
new file mode 100644
index 000000000..0b011f9a5
--- /dev/null
+++ b/.github/release-notes/v1.2.7.md
@@ -0,0 +1,40 @@
+# Memmy v1.2.7
+
+## Highlights
+
+- Expanded project collaboration with shared tasks, project instructions, knowledge lookup, invitations, and clearer local-to-cloud project sharing.
+- Unified recording views and conversation-scoped recording cards, with improved playback, transcript navigation, and retained audio when transcription fails.
+- Refined the home page and the connections/tools hub, including project-aware files, connection status, filtering, and a single project-creation dialog per window.
+
+## Project collaboration
+
+- Reuse an existing linked cloud project when the same local project is shared again, and keep one local-project association when rebinding.
+- Show project identifiers in selection and conflict messages so supported project-management commands can distinguish projects with the same name.
+- Serialize collaboration link writes and preserve background upload progress while keeping local selections and project bindings consistent.
+- Restore completed onboarding after reinstall and preserve cloud-controlled demo eligibility.
+- Improve board header hit areas, project sharing feedback, and coordination between launch prompts and collaboration onboarding.
+- Remove the cross-device member-assistance workflow from the desktop collaboration experience. Shared project tasks and project knowledge remain available.
+
+## Recordings and desktop
+
+- Keep recording cards scoped to their owning conversation and provide a consistent recording/transcript view.
+- Preserve captured audio when transcription fails, show recovery status, and improve recording archive and summary delivery flows.
+- Repair WebM duration metadata and improve playback and transcript navigation.
+- Restore the sidebar recording shortcut after viewing an existing recording and improve recording-panel width and navigation.
+- Scope the task file panel to the selected project and refine home recommendations, tool filters, and connection presentation.
+
+## Agent, runtime, and reliability
+
+- Improve OpenAI-compatible Responses protocol negotiation, reasoning and tool-call continuity across session reloads, and streaming output handling.
+- Repair Windows Memory startup and plugin activation when optional upload or recording directories do not yet exist.
+- Keep the backend available when launch-specific MCP configuration is temporarily locked, and refresh Agent connections after both bridge entries have been updated.
+- Retain managed TeX and Office rendering support while moving Office runtime preparation into the background, with download, extraction and verification progress. Operations that need native tools wait for preparation.
+- Revalidate Windows local-reader consent checks when file permissions change.
+
+## Upgrade notes
+
+- Desktop, Agent, Backend, and native application metadata use `1.2.7`. The Memory service, viewer, and CLI remain independently versioned at `2.1.7`.
+- In a shared project, new task drafts default to sharing with project members. Turn sharing off before the first message to keep that task local; existing tasks retain their saved sharing state.
+- Stopping project sharing keeps the local project and its tasks, and saves its shared background and guidelines locally. Rebinding changes the local association without deleting the previous cloud project.
+- Office runtime preparation may still be needed on first native use. The MCP configuration recovery above applies to the bridge-writing stage, not every earlier configuration migration.
+- Installation, in-place upgrade, signed-package acceptance, independent review, and publication remain separate release checks. Final package artifacts must be traced to the reviewed release candidate.
diff --git a/.github/workflows/linux-cli-installer.yml b/.github/workflows/linux-cli-installer.yml
index 7e14aa4b9..1cc31524c 100644
--- a/.github/workflows/linux-cli-installer.yml
+++ b/.github/workflows/linux-cli-installer.yml
@@ -70,7 +70,12 @@ jobs:
- uses: actions/setup-go@v5
with:
go-version: '1.22'
+ # onnxruntime-node tries to download the CUDA execution-provider binaries from a GitHub
+ # release on Linux x64, and that artifact is no longer published. Memory's embedder pins
+ # device: "cpu", so the CPU binaries bundled in the npm package are all we need.
- run: npm ci
+ env:
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
- run: npm ci --prefix App/memmy-agent
- name: Resolve and verify version
id: version
diff --git a/.github/workflows/main-sync-validation.yml b/.github/workflows/main-sync-validation.yml
index 3b1d0d526..a92c66f9c 100644
--- a/.github/workflows/main-sync-validation.yml
+++ b/.github/workflows/main-sync-validation.yml
@@ -72,6 +72,10 @@ jobs:
node-version: 22
cache: npm
- name: Install declared workspace and Agent dependencies
+ env:
+ # The CUDA execution-provider artifact onnxruntime-node downloads is no longer published;
+ # Memory's embedder pins device: "cpu", so the bundled CPU binaries suffice.
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
run: |-
npm ci
npm ci --prefix App/memmy-agent
diff --git a/.github/workflows/memmy-regression-evidence.yml b/.github/workflows/memmy-regression-evidence.yml
index 4e1a164b8..ded4adc9e 100644
--- a/.github/workflows/memmy-regression-evidence.yml
+++ b/.github/workflows/memmy-regression-evidence.yml
@@ -34,9 +34,18 @@ jobs:
node-version: 22
cache: npm
- name: Install declared workspace and Agent dependencies
+ env:
+ # The CUDA execution-provider artifact onnxruntime-node downloads is no longer published;
+ # Memory's embedder pins device: "cpu", so the bundled CPU binaries suffice.
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
run: |
npm ci
npm install --prefix App/memmy-agent --ignore-scripts --no-audit --no-fund
+ - name: Build shared test dependencies
+ run: |
+ npm run build -w @memmy/migrations
+ npm run build -w @memmy/agent-source-core
+ npm run build -w @memmy/local-api-contracts
- name: Build Agent test dependencies
run: npm --prefix App/memmy-agent run pretest
- name: Run card regression and performance proxy tests
diff --git a/.github/workflows/memory-release.yml b/.github/workflows/memory-release.yml
index da445a357..534c33ffc 100644
--- a/.github/workflows/memory-release.yml
+++ b/.github/workflows/memory-release.yml
@@ -23,7 +23,11 @@ jobs:
with:
node-version: 22
cache: npm
+ # The CUDA execution-provider artifact onnxruntime-node downloads is no longer published;
+ # Memory's embedder pins device: "cpu", so the bundled CPU binaries suffice.
- run: npm ci
+ env:
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
- run: npm run typecheck -w @memmy/memory
- run: npm test -w @memmy/memory
- run: npm run build -w @memmy/migrations
@@ -56,6 +60,8 @@ jobs:
node-version: 22
cache: npm
- run: npm ci
+ env:
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
- name: Resolve version
id: version
shell: bash
diff --git a/.github/workflows/office-plugin.yml b/.github/workflows/office-plugin.yml
index 42c0196e5..5f2fe307b 100644
--- a/.github/workflows/office-plugin.yml
+++ b/.github/workflows/office-plugin.yml
@@ -39,6 +39,15 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: 24
+ - name: Test pinned build-input provisioning
+ run: node --test plugins/office/tests/build-inputs.test.mjs plugins/office/tests/provision-windows.test.mjs
+ - name: Identify pinned release-build inputs
+ id: office-inputs
+ run: node plugins/office/scripts/office-build-inputs.mjs --cache-key >> "$GITHUB_OUTPUT"
+ - uses: actions/cache@v4
+ with:
+ path: ${{ runner.temp }}/office-input-cache
+ key: ${{ steps.office-inputs.outputs.key }}
- name: Provision release-build inputs on macOS
if: runner.os == 'macOS'
run: |
@@ -46,26 +55,16 @@ jobs:
brew install poppler
- name: Provision release-build inputs on Windows
if: runner.os == 'Windows'
- shell: pwsh
- run: |
- choco install libreoffice-fresh --version=26.2.6 -y --no-progress
- if ($LASTEXITCODE -ne 0) { throw 'LibreOffice installation failed' }
- $archive = Join-Path $env:RUNNER_TEMP 'poppler.zip'
- Invoke-WebRequest 'https://github.com/oschwartz10612/poppler-windows/releases/download/v26.09.0-0/Release-26.09.0-0.zip' -OutFile $archive
- if ((Get-FileHash $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne '7a6f256a0ddf7536182246a5733331bf4677cbcc34f4663774947ad34556c8d0') {
- # The exact upstream digest is pinned; never continue with an unchecked download.
- throw 'Poppler archive integrity check failed'
- }
- $unpacked = Join-Path $env:RUNNER_TEMP 'poppler'
- Expand-Archive $archive $unpacked
- $root = Get-ChildItem $unpacked -Directory | Where-Object { Test-Path (Join-Path $_.FullName 'Library/bin/pdfinfo.exe') } | Select-Object -First 1
- if (!$root) { throw 'Poppler portable layout not found' }
- "OFFICE_BUILD_POPPLER=$($root.FullName)" >> $env:GITHUB_ENV
+ run: node plugins/office/scripts/provision-windows.mjs
- name: Install plugin build dependencies
run: npm ci --prefix plugins/office
- name: Prepare and smoke-test portable renderer
run: node plugins/office/scripts/prepare-runtime.mjs "$RUNNER_TEMP/office-runtime-tree"
- name: Install build dependencies
+ env:
+ # The CUDA execution-provider artifact onnxruntime-node downloads is no longer published;
+ # Memory's embedder pins device: "cpu", so the bundled CPU binaries suffice.
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
run: |
npm ci
npm install --prefix App/memmy-agent --ignore-scripts --no-audit --no-fund
@@ -97,3 +96,4 @@ jobs:
plugins/office/release/
${{ runner.temp }}/office-qa/
${{ runner.temp }}/office-e2e.json
+ ${{ runner.temp }}/office-build-inputs/libreoffice-msi.log
diff --git a/.github/workflows/runtime-artifacts.yml b/.github/workflows/runtime-artifacts.yml
index 7854d5629..b5a6d8727 100644
--- a/.github/workflows/runtime-artifacts.yml
+++ b/.github/workflows/runtime-artifacts.yml
@@ -57,6 +57,10 @@ jobs:
architecture: ${{ matrix.arch }}
cache: npm
- name: Install build dependencies
+ env:
+ # The CUDA execution-provider artifact onnxruntime-node downloads is no longer published;
+ # Memory's embedder pins device: "cpu", so the bundled CPU binaries suffice.
+ ONNXRUNTIME_NODE_INSTALL_CUDA: skip
run: npm ci --no-audit --no-fund
- name: Install Agent build dependencies
if: github.event_name == 'workflow_dispatch' && inputs.runtime != 'memory'
diff --git a/.github/workflows/windows-computer-history-validation.yml b/.github/workflows/windows-computer-history-validation.yml
index 5519bcce2..bf8cb3c32 100644
--- a/.github/workflows/windows-computer-history-validation.yml
+++ b/.github/workflows/windows-computer-history-validation.yml
@@ -10,8 +10,12 @@ on:
- "Memory/tests/service/read-model/panel-stats-migration.test.ts"
- "Memory/tests/fixtures/panel-cache-fixture.ts"
- "App/shell/desktop/src/main/windows-launch-at-login.ts"
+ - "App/shell/desktop/src/main/windows-update-launcher.ts"
+ - "App/shell/desktop/build/installer-win-unsigned.nsh"
- "App/shell/desktop/src/main/main.ts"
- "App/shell/desktop/tests/windows-launch-at-login*.test.ts"
+ - "App/shell/desktop/tests/windows-update-launcher.test.ts"
+ - "App/shell/desktop/tests/windows-installer-launcher.test.ts"
- "App/shell/desktop/tests/fixtures/windows-launch-at-login.cjs"
- "App/native-computer-history/**"
- "App/native-computer-use/**"
@@ -249,11 +253,11 @@ jobs:
node node_modules/vitest/vitest.mjs run tests/windows-memory-workflow.test.ts tests/windows-provider-receipt-workflow.test.ts
if ($LASTEXITCODE -ne 0) { throw 'Windows workflow and receipt contract regressions failed' }
$loginResults = Join-Path $env:RUNNER_TEMP 'windows-login-results.json'
- node node_modules/vitest/vitest.mjs run App/shell/desktop/tests/windows-launch-at-login.test.ts App/shell/desktop/tests/windows-launch-at-login-electron.test.ts --reporter=default --reporter=json --outputFile=$loginResults
- if ($LASTEXITCODE -ne 0) { throw 'Windows Electron startup regression failed' }
+ node node_modules/vitest/vitest.mjs run App/shell/desktop/tests/windows-launch-at-login.test.ts App/shell/desktop/tests/windows-launch-at-login-electron.test.ts App/shell/desktop/tests/windows-update-launcher.test.ts App/shell/desktop/tests/windows-installer-launcher.test.ts --reporter=default --reporter=json --outputFile=$loginResults
+ if ($LASTEXITCODE -ne 0) { throw 'Windows launcher and Electron startup regressions failed' }
$loginReport = Get-Content -LiteralPath $loginResults -Raw | ConvertFrom-Json
if ($loginReport.numTotalTests -lt 1 -or $loginReport.numPendingTests -ne 0 -or $loginReport.numPassedTests -ne $loginReport.numTotalTests) {
- throw 'Windows Electron startup validation must execute every selected test; skips are not accepted.'
+ throw 'Windows launcher validation must execute every selected test; skips are not accepted.'
}
npm run build -w @memmy/agent-source-core
if ($LASTEXITCODE -ne 0) { throw 'Memory fixture shared contracts build failed' }
diff --git a/.gitignore b/.gitignore
index 421e10011..f8260031a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,6 +28,7 @@ artifacts/literature-review-*.json
# not track empty directories, and `.*` above would otherwise drop the marker.
!App/memmy-agent/src/tools/computer-history/win/.gitkeep
App/backend/src/adapters/outbound/skill-writer/workspace-bridge/memmy-workspace-bridge.mjs
+App/backend/src/adapters/outbound/skill-writer/project-hook/memmy-project-runtime.mjs
Memory/src/agent-source/integration/workspace-bridge/memmy-workspace-bridge.mjs
# Office rendering executables and libraries are provisioned during packaging.
diff --git a/App/backend/local-api-contracts/src/collab-instructions.ts b/App/backend/local-api-contracts/src/collab-instructions.ts
new file mode 100644
index 000000000..44d0a0283
--- /dev/null
+++ b/App/backend/local-api-contracts/src/collab-instructions.ts
@@ -0,0 +1,350 @@
+/**
+ * 协作项目指令:云端项目自己的背景与规范,成员的本机只保存一份缓存。
+ *
+ *
它与本机项目的指令是两套东西,不共用文件、不共用键、不互相降级:本机指令属于这台电脑上的一个文件夹
+ * (见 {@code project-instructions}),协作指令属于云端的一个项目。
+ *
+ * 一条指令的生效范围不是一个目录,而是**这个项目关联了哪些 Agent 的哪些会话单位**。单位由每个 Agent
+ * 自己的组织方式决定,Memmy 在关联会话时也是按同一套单位让人选的:Claude Code 与 WorkBuddy 是工作目录、
+ * Cursor 是 workspace(多根工作区即 workspace 文件)、Codex 是它自己的项目(一个项目可含多个根目录)。
+ * 所以条目的键是 (sourceId, groupId),而不是路径;路径只在单位本身就是目录时才出现。
+ *
+ * ```json
+ * {
+ * "version": 1,
+ * "projects": {
+ * "1853c1ee-3037-4630-9b99-f1709b1514ac": {
+ * "scopes": [
+ * { "sourceId": "memmy", "groupId": "/Users/me/.memmy/local-projects/MemOS" },
+ * { "sourceId": "claude_code", "groupId": "/Users/me/code/memmy" },
+ * { "sourceId": "cursor", "groupId": "/Users/me/work/MemOS.code-workspace" },
+ * { "sourceId": "codex", "groupId": "01a17657-0cd5-7be0-a611-3fdcd387e8ae" }
+ * ],
+ * "name": "MemOS",
+ * "members": ["孙起", "张三"],
+ * "text": "本项目负责 Memmy 桌面端的研发。",
+ * "updatedAt": "2026-10-28T13:02:11.000Z"
+ * }
+ * }
+ * }
+ * ```
+ *
+ * 条目代表的是「这个目录属于一个协作项目」,不只是「这个项目有背景与规范」:项目没写背景与规范时
+ * `text` 是空串,条目照样存在,{@link renderCollabProjectContext} 会省掉这一段、只说明项目与成员。
+ */
+import { z } from "zod";
+
+export const COLLAB_INSTRUCTIONS_FILE_NAME = "collab-project-instructions.json";
+
+/**
+ * 与云端上限一致。指令全文注入每一轮的系统提示词,所以上限按「够写完项目的背景与规范」定。
+ * 这是协作侧自己的常量:本机项目指令调整上限时不应该牵动它。
+ */
+export const MAX_COLLAB_INSTRUCTIONS_CHARS = 10_000;
+
+/** 一个成员最多缓存多少个协作项目的指令:多出的不再注入,也不让文件无限增长。 */
+export const MAX_COLLAB_INSTRUCTIONS_ENTRIES = 200;
+
+/** 一个项目最多记多少个会话单位:关联的 Agent 分组数量级,再多也不该无限增长。 */
+export const MAX_COLLAB_INSTRUCTION_SCOPES = 200;
+
+/**
+ * 项目名的长度上限。名字进注入文本的第一句与标签属性,不参与决策,所以只按「够写一个项目名」定。
+ * 写入时按它截断,读取侧的上限放宽:名字过长不该让整份文件解析失败、连带别的项目也拿不到指令。
+ */
+export const MAX_COLLAB_PROJECT_NAME_CHARS = 120;
+
+/** 一个项目最多记多少个成员名:与云端成员上限同量级,再多也不该无限增长。 */
+export const MAX_COLLAB_PROJECT_MEMBERS = 200;
+
+/** 单个成员显示名的长度上限。 */
+export const MAX_COLLAB_PROJECT_MEMBER_NAME_CHARS = 64;
+
+/** 读取侧对这两个字段的上限:宽松到不会被历史或云端数据撑破,写入时再按上面的常量收紧。 */
+const READ_NAME_MAX = 4_096;
+const READ_MEMBER_NAME_MAX = 4_096;
+const READ_MEMBERS_MAX = 1_000;
+
+/** 代表这台机器上 Memmy 自己的会话:它们的单位就是项目的工作目录。 */
+export const MEMMY_SCOPE_SOURCE = "memmy";
+
+/** 老版本只记目录时用的来源标记:任何 Agent 只要工作目录落在里面都算命中。 */
+const ANY_SOURCE = "*";
+
+export const CollabInstructionScopeSchema = z.object({
+ /** Agent 来源:claude_code / cursor / codex / workbuddy / memmy 等,与关联会话时的来源一致。 */
+ sourceId: z.string().max(64),
+ /**
+ * 该 Agent 自己的单位 id,语义由 Agent 决定:Claude Code 与 WorkBuddy 是目录路径,Cursor 是 workspace
+ * (多根工作区即 .code-workspace 文件),Codex 是它的项目 id;单独关联的会话则是会话 id。
+ */
+ groupId: z.string().max(4_096),
+ /**
+ * 这个单位覆盖的目录。Cursor 的 workspace 与 Codex 的项目都可能跨目录,只存单位 id 时从会话端无法匹配,
+ * 所以把「它盖住哪些目录」一并记下;单位本身就是目录时可省。
+ */
+ roots: z.array(z.string().max(4_096)).max(64).optional()
+}).strict();
+export type CollabInstructionScope = z.infer;
+
+export const CollabInstructionsEntrySchema = z.object({
+ scopes: z.array(CollabInstructionScopeSchema).max(MAX_COLLAB_INSTRUCTION_SCOPES).optional(),
+ /** 老版本的单个目录与目录列表;只用于读取历史文件,写入一律用 scopes。 */
+ directories: z.array(z.string().max(4_096)).max(64).optional(),
+ directory: z.string().max(4_096).optional(),
+ /**
+ * 项目名。没有背景与规范的项目也有条目,靠它告诉 Agent「这个目录属于哪个协作项目」,
+ * 所以老条目没有这个字段是正常的,读到 undefined 时按「不知道名字」处理。
+ */
+ name: z.string().max(READ_NAME_MAX).optional(),
+ /** 成员显示名;同样可能缺省,缺省时注入文本里不提成员。 */
+ members: z.array(z.string().max(READ_MEMBER_NAME_MAX)).max(READ_MEMBERS_MAX).optional(),
+ /** 背景与规范全文;项目没设定时是空串——条目仍然代表「这个目录属于一个协作项目」。 */
+ text: z.string().max(MAX_COLLAB_INSTRUCTIONS_CHARS * 4),
+ updatedAt: z.string().max(40)
+}).strict().transform((entry) => {
+ const name = collabProjectName(entry.name);
+ const members = collabProjectMembers(entry.members);
+ return {
+ scopes: normalizeScopes([
+ ...(entry.scopes ?? []),
+ // 老数据只有目录:当作「任何来源、按目录覆盖」,迁移后方向仍然正确。
+ ...(entry.directories ?? []).map((directory) => ({ sourceId: ANY_SOURCE, groupId: directory })),
+ ...(entry.directory ? [{ sourceId: ANY_SOURCE, groupId: entry.directory }] : [])
+ ]),
+ ...(name ? { name } : {}),
+ ...(members.length ? { members } : {}),
+ text: entry.text,
+ updatedAt: entry.updatedAt
+ };
+});
+export type CollabInstructionsEntry = z.infer;
+
+export const CollabInstructionsFileSchema = z.object({
+ version: z.literal(1),
+ projects: z.record(z.string().max(128), CollabInstructionsEntrySchema)
+}).strict();
+export type CollabInstructionsFile = z.infer;
+
+/** 空文件:本机还没有缓存任何协作项目的指令时就是它。 */
+export function emptyCollabInstructionsFile(): CollabInstructionsFile {
+ return { version: 1, projects: {} };
+}
+
+/**
+ * 解析文件内容。读方不只一个进程,坏文件只能当作「没有指令」:
+ * 抛错会让一次普通的任务因为别处写坏了文件而开始不了。
+ */
+export function parseCollabInstructionsFile(raw: unknown): CollabInstructionsFile {
+ const parsed = CollabInstructionsFileSchema.safeParse(raw);
+ return parsed.success ? parsed.data : emptyCollabInstructionsFile();
+}
+
+/** 目录比较用的规范化:去掉结尾分隔符,`a/` 与 `a` 是同一个目录。 */
+export function collabInstructionsDirectoryKey(directory: string): string {
+ const trimmed = directory.trim();
+ if (!trimmed) return "";
+ return trimmed.length > 1 ? trimmed.replace(/[/\\]+$/u, "") : trimmed;
+}
+
+/** 去重并丢掉空项;顺序保留,方便排障时看到先关联了哪些单位。 */
+export function normalizeScopes(scopes: readonly CollabInstructionScope[]): CollabInstructionScope[] {
+ const seen = new Set();
+ const kept: CollabInstructionScope[] = [];
+ for (const scope of scopes) {
+ const sourceId = scope.sourceId.trim();
+ const groupId = scope.groupId.trim();
+ if (!sourceId || !groupId) continue;
+ const key = `${sourceId}\u0000${groupId}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const roots = normalizeRoots(scope.roots ?? (needsRoots(groupId) ? [groupId] : []));
+ kept.push({
+ sourceId,
+ groupId: isPathLikeGroup(groupId) ? collabInstructionsDirectoryKey(groupId) : groupId,
+ ...(roots.length ? { roots } : {})
+ });
+ }
+ return kept;
+}
+
+/** 单位本身就是一个目录时,它盖住的目录就是自己。 */
+function needsRoots(groupId: string): boolean {
+ return isPathLikeGroup(groupId) && !isWorkspaceFile(groupId);
+}
+
+function normalizeRoots(roots: readonly string[]): string[] {
+ const seen = new Set();
+ const kept: string[] = [];
+ for (const root of roots) {
+ const key = collabInstructionsDirectoryKey(root);
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ kept.push(key);
+ }
+ return kept;
+}
+
+/** 这个单位本身是不是一个路径(目录或 workspace 文件)。Codex 的项目 id 不是。 */
+export function isPathLikeGroup(groupId: string): boolean {
+ return groupId.startsWith("/") || groupId.startsWith("~") || /^[A-Za-z]:[\\/]/u.test(groupId);
+}
+
+/** Cursor 的多根工作区存成 .code-workspace;它不是目录,要展开里面记录的根。 */
+export function isWorkspaceFile(groupId: string): boolean {
+ return groupId.endsWith(".code-workspace");
+}
+
+/** 某个目录是否属于某个目录单位(本身或它的子目录)。 */
+export function collabInstructionsDirectoryCovers(projectDirectory: string, directory: string): boolean {
+ const root = collabInstructionsDirectoryKey(projectDirectory);
+ const target = collabInstructionsDirectoryKey(directory);
+ if (!root || !target) return false;
+ if (root === target) return true;
+ const separator = root.includes("\\") ? "\\" : "/";
+ return target.startsWith(`${root}${separator}`);
+}
+
+/** 一个会话在这次查找里的身份:哪个 Agent、属于哪个单位、跑在哪个目录、会话本身是哪个。 */
+export interface CollabInstructionQuery {
+ sourceId: string;
+ /** 该 Agent 按自己的规则算出的单位;算不出来时为 null。 */
+ groupId?: string | null;
+ /** 会话的工作目录;单位是目录时用它兜底匹配,也用于老数据的目录覆盖。 */
+ directory?: string | null;
+ /** 会话自身的 id,用于「只关联了这一个会话」的情况。 */
+ conversationId?: string | null;
+ /**
+ * 调用方是否自己算出了精确的单位 id(例如 Codex 的项目)。算出时只认单位与会话的精确匹配,
+ * 不再用「单位覆盖的目录」兜底:Codex 的项目根可以互相嵌套,按目录兜底会把别的项目算进来。
+ */
+ unitIsExact?: boolean;
+}
+
+/**
+ * 按会话取指令:先看单位是否正好被关联,再看目录是否落在某个目录单位里,最后看是否只关联了这个会话。
+ *
+ * 三个条件都用「这个项目关联过」这一件事做判断,只是粒度不同:Codex 的项目、Cursor 的 workspace、
+ * Claude Code 的目录,或单独挑出来的一个会话。
+ */
+export function collabInstructionsFor(
+ file: CollabInstructionsFile,
+ query: CollabInstructionQuery
+): { projectId: string; entry: CollabInstructionsEntry } | null {
+ const sourceId = query.sourceId.trim();
+ if (!sourceId) return null;
+ const groupId = query.groupId?.trim() ?? "";
+ const directory = query.directory?.trim() ?? "";
+ const conversationId = query.conversationId?.trim() ?? "";
+ if (!groupId && !directory && !conversationId) return null;
+ const unitIsExact = query.unitIsExact === true && Boolean(groupId);
+
+ let matched: { projectId: string; entry: CollabInstructionsEntry; weight: number } | null = null;
+ for (const [projectId, entry] of Object.entries(file.projects)) {
+ for (const scope of entry.scopes) {
+ const weight = scopeWeight(scope, { sourceId, groupId, directory, conversationId, unitIsExact });
+ if (weight <= 0) continue;
+ if (!matched || weight > matched.weight) matched = { projectId, entry, weight };
+ }
+ }
+ return matched ? { projectId: matched.projectId, entry: matched.entry } : null;
+}
+
+/** 命中强度:单位精确命中 > 目录覆盖 > 单会话;老数据的通配来源按目录覆盖算。 */
+function scopeWeight(
+ scope: CollabInstructionScope,
+ query: { sourceId: string; groupId: string; directory: string; conversationId: string; unitIsExact: boolean }
+): number {
+ const sameSource = scope.sourceId === query.sourceId;
+ const anySource = scope.sourceId === ANY_SOURCE;
+ if (!sameSource && !anySource) return 0;
+ // 单位精确命中(钩子自己算出了同一个单位 id)优先,其次单独关联的会话,最后用单位覆盖的目录兜底。
+ if (sameSource && query.groupId && scope.groupId === query.groupId) return 300 + scope.groupId.length;
+ if (query.conversationId && scope.groupId === query.conversationId) return 200;
+ // 算出了精确单位时不再按目录兜底:Codex 的项目根会互相嵌套,兜底会把别的项目算进来。
+ if (query.unitIsExact) return 0;
+ if (query.directory) {
+ const roots = scope.roots?.length ? scope.roots : (needsRoots(scope.groupId) ? [scope.groupId] : []);
+ for (const root of roots) {
+ if (collabInstructionsDirectoryCovers(root, query.directory)) return 100 + root.length;
+ }
+ }
+ return 0;
+}
+
+/** 指令是否够短到能全文注入;超出时后端在写入前就拒绝,这里兜住历史数据。 */
+export function collabInstructionsText(value: string | null | undefined): string {
+ const text = typeof value === "string" ? value.trim() : "";
+ if (!text) return "";
+ const chars = [...text];
+ return chars.length <= MAX_COLLAB_INSTRUCTIONS_CHARS ? text : chars.slice(0, MAX_COLLAB_INSTRUCTIONS_CHARS).join("");
+}
+
+/**
+ * 项目名:换行与连续空白换成单个空格,按上限截断;没有名字时返回空串。
+ *
+ * 名字只是提示词里的一句话与一个标签属性,不是键:写与读都按同一套规则归一,
+ * 存进去的和渲染出来的一致,也方便写入侧判断「内容没变就不重写文件」。
+ */
+export function collabProjectName(value: string | null | undefined): string {
+ if (typeof value !== "string") return "";
+ return truncateChars(value.replace(/\s+/gu, " ").trim(), MAX_COLLAB_PROJECT_NAME_CHARS);
+}
+
+/** 成员显示名:去换行、去空项、按名字去重;超过人数上限的部分不再记。 */
+export function collabProjectMembers(value: readonly (string | null | undefined)[] | null | undefined): string[] {
+ if (!value?.length) return [];
+ const seen = new Set();
+ const kept: string[] = [];
+ for (const raw of value) {
+ const name = typeof raw === "string" ? truncateChars(raw.replace(/\s+/gu, " ").trim(), MAX_COLLAB_PROJECT_MEMBER_NAME_CHARS) : "";
+ if (!name || seen.has(name)) continue;
+ seen.add(name);
+ kept.push(name);
+ if (kept.length >= MAX_COLLAB_PROJECT_MEMBERS) break;
+ }
+ return kept;
+}
+
+function truncateChars(value: string, limit: number): string {
+ const chars = [...value];
+ return chars.length <= limit ? value : chars.slice(0, limit).join("").trim();
+}
+
+/**
+ * 注入用的协作项目段:这个目录属于哪个项目、成员有谁、背景与规范是什么。
+ *
+ * 它是「项目背景」而不是「指令全文」,所以三种缺省都要能出文:没有背景与规范时只留项目与成员,
+ * 没有成员时只提项目,两者都没有时也要能说清「这个目录属于一个协作项目」——不然 Agent 在已关联的
+ * 目录里仍然不知道要先查项目任务。
+ */
+export interface CollabProjectContextInput {
+ /** 项目名;不知道时留空。 */
+ name?: string | null;
+ /** 成员显示名;为空时不提成员。 */
+ members?: readonly string[] | null;
+ /** 背景与规范全文;为空时省去这一段。 */
+ text?: string | null;
+}
+
+export function renderCollabProjectContext(input: CollabProjectContextInput): string {
+ const name = collabProjectName(input.name);
+ const members = collabProjectMembers(input.members);
+ const text = collabInstructionsText(input.text);
+ const lines = [
+ name ? `` : "",
+ `当前工作目录属于${name ? ` Memmy 协作项目「${name}」` : "一个 Memmy 协作项目"}`
+ + `${members.length ? `,成员有${members.join("、")}` : ""}`
+ + ",成员在各自 Agent 里做过的任务都共享在这个项目中。",
+ "用户问到这个项目里以前做过什么、怎么定的、为什么这样做、谁在做、进展到哪时,"
+ + "即使没提成员和项目,也先用 memmy-project 在本项目的任务里查;问代码现在是什么样,以代码为准。"
+ ];
+ if (text) lines.push("", "所有者设定了以下背景与规范,在本项目中的任务里遵循:", "", text);
+ lines.push("");
+ return lines.join("\n");
+}
+
+/** 项目名进属性前收拾一下:引号换成单引号、尖括号去掉,免得把标签拆坏。 */
+function collabProjectAttribute(name: string): string {
+ return name.replace(/"/gu, "'").replace(/[<>]/gu, "");
+}
diff --git a/App/backend/local-api-contracts/src/index.ts b/App/backend/local-api-contracts/src/index.ts
index ee2764182..a92592881 100644
--- a/App/backend/local-api-contracts/src/index.ts
+++ b/App/backend/local-api-contracts/src/index.ts
@@ -35,6 +35,8 @@ export * from "./browser-task-site-permission.js";
export * from "./browser-use-site-policy.js";
export * from "./browser-cdp-readonly.js";
export * from "./browser-cdp-write.js";
+export * from "./project-instructions.js";
+export * from "./collab-instructions.js";
export const MANAGED_AGENT_DISCOVERY_PENDING_DATA_PATH = "memmy-agent://history-discovery-pending";
diff --git a/App/backend/local-api-contracts/src/memory-runtime.ts b/App/backend/local-api-contracts/src/memory-runtime.ts
index eaa9bb1bc..64ba9942c 100644
--- a/App/backend/local-api-contracts/src/memory-runtime.ts
+++ b/App/backend/local-api-contracts/src/memory-runtime.ts
@@ -1064,6 +1064,7 @@ export const ApiErrorCodeSchema = z.enum([
"model_config_changed",
"config_write_busy",
"account_model_preset_conflict",
+ "collab_quota_exceeded",
"plugin_entitlement_required"
]);
export type ApiErrorCode = z.infer;
diff --git a/App/backend/local-api-contracts/src/plugin.ts b/App/backend/local-api-contracts/src/plugin.ts
index 121ba374b..d104692f4 100644
--- a/App/backend/local-api-contracts/src/plugin.ts
+++ b/App/backend/local-api-contracts/src/plugin.ts
@@ -334,6 +334,8 @@ export type PluginHostServiceResponse = z.infer指令既属于本地项目,也属于开启了共享的协作项目,所以它不放在任何一个 Agent 自己的配置里,而是由桌面端
+ * 后端写一份本机文件,供三处只读使用:Memmy 任务的系统提示词、其他 Agent 的钩子、以及看板的项目配置。
+ * 这样本地项目与协作项目走同一条注入路径,区别只在「指令由谁维护」。
+ *
+ * 文件由后端单独写入(先写临时文件再改名),读方只解析:
+ *
+ * ```json
+ * {
+ * "version": 1,
+ * "projects": {
+ * "/Users/me/code/memmy": {
+ * "text": "本项目负责 Memmy 桌面端的研发。",
+ * "origin": "cloud",
+ * "cloudProjectId": "9f1c…",
+ * "updatedAt": "2026-10-24T12:00:00.000Z"
+ * }
+ * }
+ * }
+ * ```
+ *
+ * 键是项目任务所在目录(规范化后的绝对路径),因为三个读方都能拿到它:Memmy 任务知道会话的工作目录,
+ * 其他 Agent 的钩子拿到 cwd,看板知道本机项目根目录。
+ */
+import { z } from "zod";
+
+export const PROJECT_INSTRUCTIONS_FILE_NAME = "project-instructions.json";
+
+/**
+ * 与云端上限一致。指令全文注入每一轮的系统提示词,所以上限按「够写完项目的背景与规范」定:
+ * 1 万字与 WorkBuddy 一致。存储不是瓶颈(1 万字 UTF-8 约 30KB,云端 TEXT 列可用 64KB),
+ * 代价在每轮上下文:见 {@link MAX_PROJECT_INSTRUCTIONS_CHARS} 在注入侧的说明。
+ */
+export const MAX_PROJECT_INSTRUCTIONS_CHARS = 10_000;
+
+/** 一个项目最多记录多少条:多出的目录不会注入,也不会让文件无限增长。 */
+export const MAX_PROJECT_INSTRUCTIONS_ENTRIES = 200;
+
+export const ProjectInstructionsOriginSchema = z.enum(["local", "cloud"]);
+export type ProjectInstructionsOrigin = z.infer;
+
+export const ProjectInstructionsEntrySchema = z.object({
+ text: z.string().max(MAX_PROJECT_INSTRUCTIONS_CHARS * 4),
+ origin: ProjectInstructionsOriginSchema,
+ /** 协作项目的云端 ID;本地项目为 null。 */
+ cloudProjectId: z.string().max(64).nullable(),
+ updatedAt: z.string().max(40)
+}).strict();
+export type ProjectInstructionsEntry = z.infer;
+
+export const ProjectInstructionsFileSchema = z.object({
+ version: z.literal(1),
+ projects: z.record(z.string().max(4_096), ProjectInstructionsEntrySchema)
+}).strict();
+export type ProjectInstructionsFile = z.infer;
+
+/** 空文件:没有项目设定过指令时就是它。 */
+export function emptyProjectInstructionsFile(): ProjectInstructionsFile {
+ return { version: 1, projects: {} };
+}
+
+/**
+ * 解析文件内容。读方不只一个进程,坏文件只能当作「没有指令」:
+ * 抛错会让一次普通的任务因为别处写坏了文件而开始不了。
+ */
+export function parseProjectInstructionsFile(raw: unknown): ProjectInstructionsFile {
+ const parsed = ProjectInstructionsFileSchema.safeParse(raw);
+ return parsed.success ? parsed.data : emptyProjectInstructionsFile();
+}
+
+/** 目录 → 文件的键。去掉结尾的分隔符,`a/` 与 `a` 是同一个项目。 */
+export function projectInstructionsKey(directory: string): string {
+ const trimmed = directory.trim();
+ if (!trimmed) return "";
+ return trimmed.length > 1 ? trimmed.replace(/[/\\]+$/u, "") : trimmed;
+}
+
+/**
+ * 取某个目录的指令:命中即返回,否则返回空文本。
+ * 读方只要文本,`origin` 与时间由看板与排障使用。
+ */
+export function projectInstructionsAt(
+ file: ProjectInstructionsFile,
+ directory: string | null | undefined
+): ProjectInstructionsEntry | null {
+ if (!directory) return null;
+ return file.projects[projectInstructionsKey(directory)] ?? null;
+}
+
+/** 指令是否够短到能全文注入;超出时后端在写入前就拒绝,这里兜住历史数据。 */
+export function projectInstructionsText(value: string | null | undefined): string {
+ const text = typeof value === "string" ? value.trim() : "";
+ if (!text) return "";
+ const chars = [...text];
+ return chars.length <= MAX_PROJECT_INSTRUCTIONS_CHARS ? text : chars.slice(0, MAX_PROJECT_INSTRUCTIONS_CHARS).join("");
+}
diff --git a/App/backend/local-api-contracts/tests/collab-instructions.test.ts b/App/backend/local-api-contracts/tests/collab-instructions.test.ts
new file mode 100644
index 000000000..53ae3a2be
--- /dev/null
+++ b/App/backend/local-api-contracts/tests/collab-instructions.test.ts
@@ -0,0 +1,163 @@
+/**
+ * 协作项目缓存契约:新旧条目的解析、按会话单位匹配,以及注入用那一段的渲染。
+ *
+ * 三种缺省都要能出文:没写背景与规范、没有成员、没有项目名——没写背景与规范的项目最要紧,
+ * 它关联的目录里的 Agent 靠这一段知道「当前目录属于哪个协作项目」。
+ */
+import { describe, expect, it } from "vitest";
+import {
+ MAX_COLLAB_INSTRUCTIONS_CHARS,
+ MAX_COLLAB_PROJECT_MEMBERS,
+ collabInstructionsFor,
+ emptyCollabInstructionsFile,
+ parseCollabInstructionsFile,
+ renderCollabProjectContext
+} from "../src/collab-instructions.js";
+
+const DIRECTORY = "/Users/me/.memmy/local-projects/MemOS";
+
+function fileWith(entry: Record) {
+ return { version: 1, projects: { "p-1": entry } };
+}
+
+describe("parseCollabInstructionsFile", () => {
+ it("reads an entry from before the project name and members existed", () => {
+ const file = parseCollabInstructionsFile(fileWith({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY }],
+ text: "团队约定",
+ updatedAt: "2026-10-28T12:00:00.000Z"
+ }));
+ expect(file.projects["p-1"]).toEqual({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY, roots: [DIRECTORY] }],
+ text: "团队约定",
+ updatedAt: "2026-10-28T12:00:00.000Z"
+ });
+ });
+
+ it("reads the project name and members of a newer entry, keeping both optional", () => {
+ const file = parseCollabInstructionsFile(fileWith({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY }],
+ name: " MemOS\n实验室 ",
+ members: ["孙起", " 张三 ", "孙起", ""],
+ text: "",
+ updatedAt: "2026-10-28T12:00:00.000Z"
+ }));
+ // 名字去掉换行与多余空白,成员去空项、按名字去重。
+ expect(file.projects["p-1"]).toMatchObject({ name: "MemOS 实验室", members: ["孙起", "张三"], text: "" });
+
+ const without = parseCollabInstructionsFile(fileWith({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY }],
+ name: "",
+ members: [],
+ text: "团队约定",
+ updatedAt: "2026-10-28T12:00:00.000Z"
+ }));
+ // 空名字与空成员不留在条目里,读方只需判断有没有。
+ expect(without.projects["p-1"]).not.toHaveProperty("name");
+ expect(without.projects["p-1"]).not.toHaveProperty("members");
+ });
+
+ it("drops an over-long member list instead of the whole file", () => {
+ const members = Array.from({ length: MAX_COLLAB_PROJECT_MEMBERS + 5 }, (_, index) => `成员${index}`);
+ expect(parseCollabInstructionsFile(fileWith({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY }],
+ members,
+ text: "",
+ updatedAt: "2026-10-28T12:00:00.000Z"
+ })).projects["p-1"]?.members).toHaveLength(MAX_COLLAB_PROJECT_MEMBERS);
+ });
+
+ it("treats a file with an unknown field as no cache at all", () => {
+ expect(parseCollabInstructionsFile(fileWith({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY }],
+ text: "",
+ updatedAt: "2026-10-28T12:00:00.000Z",
+ unknown: true
+ }))).toEqual(emptyCollabInstructionsFile());
+ });
+});
+
+describe("collabInstructionsFor", () => {
+ it("matches an entry that carries no rules: the project is there, the text is empty", () => {
+ const file = parseCollabInstructionsFile(fileWith({
+ scopes: [{ sourceId: "memmy", groupId: DIRECTORY }],
+ name: "MemOS",
+ members: ["孙起"],
+ text: "",
+ updatedAt: "2026-10-28T12:00:00.000Z"
+ }));
+ const hit = collabInstructionsFor(file, { sourceId: "memmy", directory: `${DIRECTORY}/packages/app` });
+ expect(hit).toMatchObject({ projectId: "p-1", entry: { name: "MemOS", members: ["孙起"], text: "" } });
+ });
+});
+
+describe("renderCollabProjectContext", () => {
+ it("renders the whole paragraph when everything is known", () => {
+ expect(renderCollabProjectContext({
+ name: "MemOS",
+ members: ["孙起", "张三"],
+ text: "团队约定:先看 PRD。"
+ })).toBe(
+ [
+ '',
+ "当前工作目录属于 Memmy 协作项目「MemOS」,成员有孙起、张三,成员在各自 Agent 里做过的任务都共享在这个项目中。",
+ "用户问到这个项目里以前做过什么、怎么定的、为什么这样做、谁在做、进展到哪时,即使没提成员和项目,也先用 memmy-project 在本项目的任务里查;问代码现在是什么样,以代码为准。",
+ "",
+ "所有者设定了以下背景与规范,在本项目中的任务里遵循:",
+ "",
+ "团队约定:先看 PRD。",
+ ""
+ ].join("\n")
+ );
+ });
+
+ it("drops the rules part when the project has none", () => {
+ expect(renderCollabProjectContext({ name: "MemOS", members: ["孙起"], text: "" })).toBe(
+ [
+ '',
+ "当前工作目录属于 Memmy 协作项目「MemOS」,成员有孙起,成员在各自 Agent 里做过的任务都共享在这个项目中。",
+ "用户问到这个项目里以前做过什么、怎么定的、为什么这样做、谁在做、进展到哪时,即使没提成员和项目,也先用 memmy-project 在本项目的任务里查;问代码现在是什么样,以代码为准。",
+ ""
+ ].join("\n")
+ );
+ });
+
+ it("drops the member clause when there are no members", () => {
+ expect(renderCollabProjectContext({ name: "MemOS", members: [], text: "团队约定" })).toBe(
+ [
+ '',
+ "当前工作目录属于 Memmy 协作项目「MemOS」,成员在各自 Agent 里做过的任务都共享在这个项目中。",
+ "用户问到这个项目里以前做过什么、怎么定的、为什么这样做、谁在做、进展到哪时,即使没提成员和项目,也先用 memmy-project 在本项目的任务里查;问代码现在是什么样,以代码为准。",
+ "",
+ "所有者设定了以下背景与规范,在本项目中的任务里遵循:",
+ "",
+ "团队约定",
+ ""
+ ].join("\n")
+ );
+ });
+
+ it("still says the folder belongs to a collab project when nothing else is known", () => {
+ expect(renderCollabProjectContext({})).toBe(
+ [
+ "",
+ "当前工作目录属于一个 Memmy 协作项目,成员在各自 Agent 里做过的任务都共享在这个项目中。",
+ "用户问到这个项目里以前做过什么、怎么定的、为什么这样做、谁在做、进展到哪时,即使没提成员和项目,也先用 memmy-project 在本项目的任务里查;问代码现在是什么样,以代码为准。",
+ ""
+ ].join("\n")
+ );
+ });
+
+ it("keeps the tag intact when the name carries quotes or line breaks", () => {
+ const rendered = renderCollabProjectContext({ name: '我的"项目"\n第二行', text: "" });
+ // 标签属性里换行已换成空格、双引号换成单引号,标签不会被拆坏;正文里保留项目本来的写法。
+ expect(rendered.startsWith(``)).toBe(true);
+ expect(rendered).toContain('当前工作目录属于 Memmy 协作项目「我的"项目" 第二行」');
+ });
+
+ it("cuts the rules at the same limit the cache enforces", () => {
+ const rendered = renderCollabProjectContext({ name: "MemOS", members: ["孙起"], text: "字".repeat(MAX_COLLAB_INSTRUCTIONS_CHARS + 50) });
+ const body = rendered.split("\n").at(-2) ?? "";
+ expect(body).toHaveLength(MAX_COLLAB_INSTRUCTIONS_CHARS);
+ });
+});
diff --git a/App/backend/src/adapters/inbound/local-api/routes/account.ts b/App/backend/src/adapters/inbound/local-api/routes/account.ts
index c415b2e19..8ad5de68d 100644
--- a/App/backend/src/adapters/inbound/local-api/routes/account.ts
+++ b/App/backend/src/adapters/inbound/local-api/routes/account.ts
@@ -5,8 +5,6 @@ import {
AccountProfileViewSchema,
AccountSessionViewSchema,
AvatarOptionSchema,
- LotteryRewardAckInputSchema,
- LotteryRewardSchema,
TaskTokenGiftNoticeSchema,
TaskTokenGiftAckInputSchema,
OkResponseSchema,
@@ -126,25 +124,6 @@ export function registerAccountRoutes(app: FastifyInstance, options: RegisterAcc
})
);
- app.get(
- "/api/account/lottery/reward",
- { preHandler: options.authenticateRuntimeToken },
- withErrorEnvelope(async (_request, reply) => {
- const response = LotteryRewardSchema.parse(await options.account.getLotteryReward());
- return reply.send(response);
- })
- );
-
- app.post(
- "/api/account/lottery/reward/ack",
- { preHandler: options.authenticateRuntimeToken },
- withErrorEnvelope(async (request, reply) => {
- const input = LotteryRewardAckInputSchema.parse(request.body);
- const response = OkResponseSchema.parse(await options.account.ackLotteryReward(input));
- return reply.send(response);
- })
- );
-
app.post(
"/api/account/task-token-gift/ensure",
{ preHandler: options.authenticateRuntimeToken },
diff --git a/App/backend/src/adapters/inbound/local-api/routes/collab.ts b/App/backend/src/adapters/inbound/local-api/routes/collab.ts
new file mode 100644
index 000000000..ef178fc76
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/routes/collab.ts
@@ -0,0 +1,535 @@
+/** Online project routes: projects, associated sessions, and references from other agents. */
+import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { MAX_COLLAB_INSTRUCTIONS_CHARS } from "@memmy/local-api-contracts";
+import { CollabError, sinceWindowMs, type CollabService, type DemoEndReason } from "../../../../services/collab-service.js";
+import type { CollabAgentAccessService } from "../../../../services/collab-agent-access-service.js";
+import { connectCollabAgent, removeCollabAgent } from "../../../../services/collab-added-agents.js";
+import { withErrorEnvelope } from "../../../../services/error-envelope.js";
+
+export interface RegisterCollabRoutesOptions {
+ collab: CollabService;
+ /** 「在其他 Agent 中使用协作项目」的授权:设置页与授权弹窗读写它。 */
+ agentAccess?: CollabAgentAccessService;
+ authenticateRuntimeToken: (request: FastifyRequest, reply: FastifyReply) => Promise;
+ recallProjectKnowledge?: (query: string, projectId: string) => Promise<{ enabled: boolean; evidence: unknown[]; projectOnly?: boolean }>;
+}
+
+const ProjectIdSchema = z.string().regex(/^[A-Za-z0-9-]{1,36}$/u, "项目 ID 无效");
+/** 知识库 id 是 UUID,和项目 id 同一套字符。 */
+const BaseIdSchema = ProjectIdSchema;
+const KnowledgeLinkSchema = z.object({ baseId: BaseIdSchema }).strict();
+const CreateProjectSchema = z.object({
+ name: z.string().trim().min(1, "请填写项目名称").max(20, "项目名称不超过 20 个字"),
+ /** The folder the person picked for the project's tasks; a managed folder is used when absent. */
+ directory: z.string().trim().min(1).max(4_000).optional(),
+ /**
+ * 新手引导的演示:只在桌面端认为「本人第一次创建共享项目」时带。是否真的演示由云端判断,
+ * 不能演示时照常只建项目。
+ */
+ demo: z.boolean().optional(),
+ /**
+ * 发起这次共享的本机项目:同一个本机项目重复共享时复用它已有的在线项目,云端也按它去重。
+ * 旧客户端不带这个字段,行为不变。
+ */
+ localProjectId: z.string().trim().min(1).max(200).optional()
+}).strict();
+/** 演示的心跳与结束:步骤只用于排查,结束原因按约定取值。 */
+const DemoHeartbeatSchema = z.object({ step: z.enum(["1", "2", "3", "finish"]) }).strict();
+const DemoEndSchema = z.object({ reason: z.enum(["finished", "exited", "skipped", "left"]) }).strict();
+const BindProjectSchema = z.object({ localProjectId: z.string().min(1).max(200) }).strict();
+const WorkingDirectorySchema = z.object({
+ /** Names the managed folder after the project instead of its generated id. */
+ name: z.string().trim().min(1).max(200).optional(),
+ directory: z.string().trim().min(1).max(4_000).optional()
+}).strict();
+const SyncSchema = z.object({
+ tasks: z.boolean().optional(),
+ /** With `tasks`: only this project, which is what a board opening needs. */
+ projectId: ProjectIdSchema.optional()
+}).strict();
+const SessionListSchema = z.object({
+ q: z.string().max(200).optional(),
+ member: z.enum(["me", "others"]).optional(),
+ offset: z.coerce.number().int().min(0).max(100_000).optional(),
+ limit: z.coerce.number().int().min(1).max(100).optional()
+});
+const CandidatesSchema = z.object({
+ projectId: ProjectIdSchema,
+ q: z.string().max(200).optional(),
+ limit: z.coerce.number().int().min(1).max(20).optional()
+});
+const SourceIdSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,31}$/u);
+/** 用户添加的 Agent 的 sourceId 形如 `added-qoder-82ef827e`,与内置来源同一套字符。 */
+const AgentSourceSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,40}$/u, "Agent ID 无效");
+const AgentAccessSchema = z.object({ granted: z.boolean() }).strict();
+const AgentAccessInstallSchema = z.object({ sourceIds: z.array(AgentSourceSchema).max(100).optional() }).strict();
+const AgentEnabledSchema = z.object({ enabled: z.boolean() }).strict();
+const ConversationIdSchema = z.string().min(1).max(200);
+const LinksSchema = z.object({
+ groups: z.array(z.object({
+ sourceId: SourceIdSchema,
+ groupId: z.string().min(1).max(1_000),
+ excluded: z.array(ConversationIdSchema).max(500)
+ }).strict()).max(100),
+ sessions: z.array(z.object({ sourceId: SourceIdSchema, conversationId: ConversationIdSchema }).strict()).max(500)
+}).strict();
+const LocalSessionsSchema = z.object({
+ query: z.string().max(200).optional(),
+ sourceIds: z.array(z.string().max(32)).max(20).optional(),
+ limit: z.number().int().min(1).max(500).optional(),
+ fresh: z.boolean().optional()
+}).strict();
+const SearchSchema = z.object({
+ q: z.string().max(200).optional(),
+ member: z.string().max(100).optional(),
+ project: z.string().max(100).optional(),
+ limit: z.coerce.number().int().min(1).max(20).optional(),
+ since: z.string().max(10).optional()
+ .refine((value) => value === undefined || sinceWindowMs(value) !== null, "--since 的写法如 7d、24h 或 2w")
+});
+const TurnNumberSchema = z.number().int().min(1).max(100_000);
+/** What `sessions read` prints inline; the CLI always sends one, the @ menu never does. */
+const ReadViewSchema = z.object({
+ turns: z.object({ from: TurnNumberSchema, to: TurnNumberSchema }).strict().optional(),
+ around: TurnNumberSchema.optional(),
+ find: z.string().trim().min(1).max(500).optional(),
+ all: z.boolean().optional()
+}).strict().refine((view) => Object.keys(view).length <= 1, "只能指定一种读取范围");
+const ReadSchema = z.object({ reference: z.string().trim().min(1).max(2_000), view: ReadViewSchema.optional() }).strict();
+const ConnectAgentSchema = z.object({
+ name: z.string().trim().min(1).max(40),
+ /** 用户填的技能目录;留空时由添加任务自己去查找,不在这里猜。 */
+ skillDirectory: z.string().trim().min(1).max(4_000)
+}).strict();
+const RemoveAgentSchema = z.object({ name: z.string().trim().min(1).max(40) }).strict();
+/** Adds the current local task. The project name is optional so a partial name can be answered with the next command. */
+const AddSessionSchema = z.object({
+ project: z.string().trim().min(1).max(100).optional(),
+ cwd: z.string().trim().min(1).max(4_000).optional(),
+ hint: z.string().trim().min(1).max(500).optional(),
+ /** Set together: the conversation the command is running inside. */
+ sourceId: SourceIdSchema.optional(),
+ conversationId: ConversationIdSchema.optional(),
+ /** 用户添加的 Agent 交上来的任务:全部轮次,附带来源 Agent 的名称与标题。 */
+ submission: z.object({
+ agentName: z.string().trim().min(1).max(40),
+ title: z.string().trim().min(1).max(200),
+ turns: z.array(z.object({
+ question: z.string().trim().min(1).max(8_000),
+ reply: z.string().trim().min(1).max(20_000),
+ at: z.string().trim().min(1).max(40).optional()
+ }).strict()).min(1).max(500),
+ /** Agent 明确给出的记录文件;不给时由 Memmy 在该 Agent 的配置目录里按原文搜索。 */
+ sourcePath: z.string().trim().min(1).max(4_000).optional()
+ }).strict().optional()
+}).strict();
+const SearchKnowledgeSchema = z.object({
+ query: z.string().trim().min(1).max(8000),
+ project: z.string().trim().min(1).max(100).optional(),
+ sourceId: SourceIdSchema.optional(),
+ conversationId: ConversationIdSchema.optional()
+}).strict().refine((value) => Boolean(value.sourceId) === Boolean(value.conversationId), "会话身份不完整");
+const RenameProjectSchema = z.object({
+ name: z.string().trim().min(1, "请填写项目名称").max(20, "项目名称不超过 20 个字")
+}).strict();
+const InstructionsSchema = z.object({
+ instructions: z.string().max(MAX_COLLAB_INSTRUCTIONS_CHARS * 4),
+ /** 看板带来的本机项目目录,仅用于记下“这个目录属于哪个协作项目”,不是指令的键。 */
+ directory: z.string().trim().min(1).max(4_096)
+ .refine((value) => value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value), "项目目录需为绝对路径")
+ .optional()
+}).strict();
+const ProjectTasksSchema = z.object({
+ /** Conversation ids of the project's Memmy sessions that members may read. */
+ included: z.array(ConversationIdSchema).max(500)
+}).strict();
+/** 一条任务的共享开关。 */
+const TaskSharingSchema = z.object({ shared: z.boolean() }).strict();
+/** 在 Memmy 的任务里用 `memmy-project session share` 开启/关闭这条任务的共享。 */
+const ShareCurrentTaskSchema = z.object({
+ conversationId: ConversationIdSchema,
+ shared: z.boolean(),
+ project: z.string().trim().min(1).max(100).optional()
+}).strict();
+/**
+ * Cloud account IDs are numeric snowflake ids, 19 digits for accounts created by the assignment strategy (`agent_user.id`).
+ * The upper bound matches a signed 64-bit column, so real accounts are never rejected by this local check.
+ */
+const UserIdSchema = z.string().regex(/^[0-9]{1,19}$/u, "成员 ID 无效");
+const UpdateProjectSchema = z.object({ joinMode: z.enum(["direct", "approval"]) }).strict();
+/** No one is made owner here: there is no ownership transfer. */
+const MemberRoleSchema = z.object({ role: z.enum(["admin", "member"]) }).strict();
+/** The pasted link, or the whole copied invite text. */
+const InviteReferenceSchema = z.string().trim().min(1, "请粘贴邀请链接").max(2_000);
+const PreviewInviteSchema = z.object({ reference: InviteReferenceSchema }).strict();
+const JoinSchema = z.object({
+ reference: InviteReferenceSchema,
+ /** The folder the person picked for the project's tasks; a managed folder is used when absent. */
+ directory: z.string().trim().min(1).max(4_000).optional(),
+ /**
+ * 加入时顺手改的昵称,可不填:不填就沿用账号原来的名字。
+ * 填了要跟本项目现有成员不重名,由云端判定,这里只卡长度。
+ */
+ nickname: z.string().trim().max(32, "昵称不超过 32 个字").optional()
+}).strict();
+
+export function registerCollabRoutes(app: FastifyInstance, options: RegisterCollabRoutesOptions): void {
+ const guard = { preHandler: options.authenticateRuntimeToken };
+
+ app.get("/api/collab/projects", guard, withErrorEnvelope(async (_request, reply) =>
+ reply.send(await options.collab.listProjects())));
+
+ // Agents added on this computer, read from its own file: the board names their tasks with these names,
+ // and the cloud only knows the generated source id.
+ app.get("/api/collab/agents", guard, withErrorEnvelope(async (_request, reply) =>
+ reply.send({ agents: await options.collab.listAddedAgents() })));
+
+ // 等自己审核的加入申请,跨项目一次给出:邀请人的 Memmy 轮询它并在屏幕上弹窗。
+ app.get("/api/collab/join-requests", guard, withErrorEnvelope(async (_request, reply) =>
+ reply.send({ requests: await options.collab.joinRequests() })));
+
+ app.post("/api/collab/projects", guard, withErrorEnvelope(async (request, reply) => {
+ const input = CreateProjectSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.createProject(
+ input.name,
+ input.directory,
+ input.demo === undefined && input.localProjectId === undefined
+ ? undefined
+ : { demo: input.demo, localProjectId: input.localProjectId }
+ ));
+ }));
+
+ // 新手引导的演示:演示期间每 30 秒一次心跳,步骤变化时立即补一次;结束时叫云端把演示成员移出项目。
+ app.post<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/demo/heartbeat", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = DemoHeartbeatSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.demoHeartbeat(projectId, input.step));
+ }));
+
+ app.post<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/demo/end", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = DemoEndSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.demoEnd(projectId, input.reason as DemoEndReason));
+ }));
+
+ // Projects created before binding existed, and tasks that lost their local project, get one on demand.
+ // The board polls this while an association runs, so sessions appear as they are uploaded.
+ app.get<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/sync-progress", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.getSyncProgress(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.post<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/working-directory", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = WorkingDirectorySchema.parse(request.body ?? {});
+ return reply.send(await options.collab.ensureWorkingDirectory(projectId, input.name, input.directory));
+ }));
+
+ app.put<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/binding", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = BindProjectSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.bindLocalProject(projectId, input.localProjectId));
+ }));
+
+ app.get<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/sessions", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = SessionListSchema.parse(request.query ?? {});
+ return reply.send(await options.collab.listSessions(projectId, {
+ ...(input.q === undefined ? {} : { query: input.q }),
+ ...(input.member === undefined ? {} : { member: input.member }),
+ ...(input.offset === undefined ? {} : { offset: input.offset }),
+ ...(input.limit === undefined ? {} : { limit: input.limit })
+ }));
+ }));
+
+ // The board's session reader and the @ menu both read one session without downloading a file.
+ app.get<{ Params: { sessionId: string } }>("/api/collab/sessions/:sessionId", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.readSessionDetail(ProjectIdSchema.parse((request.params as { sessionId: string }).sessionId)))));
+
+ // The @ menu offers sessions of the project the task belongs to; a reference never leaves that project.
+ app.get("/api/collab/sessions/candidates", guard, withErrorEnvelope(async (request, reply) => {
+ const input = CandidatesSchema.parse(request.query ?? {});
+ return reply.send(await options.collab.candidateSessions(input.projectId, {
+ ...(input.q === undefined ? {} : { query: input.q }),
+ ...(input.limit === undefined ? {} : { limit: input.limit })
+ }));
+ }));
+
+ // Sharing a project uploads the Memmy sessions chosen here; the rest stay on this computer.
+ app.get<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/tasks", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.listProjectTasks(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.put<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/tasks", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = ProjectTasksSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.saveProjectTasks(projectId, input.included));
+ }));
+
+ // 一条 Memmy 任务的共享开关:没有记录时视为不共享,开启才上传,关闭会删掉云端副本。
+ // 桌面端在已共享项目里新建任务时默认开启,会话建立时调用这里写入。
+ app.get<{ Params: { projectId: string; conversationId: string } }>("/api/collab/projects/:projectId/tasks/:conversationId/sharing", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; conversationId: string };
+ return reply.send(await options.collab.getTaskSharing(
+ ProjectIdSchema.parse(params.projectId),
+ ConversationIdSchema.parse(params.conversationId)
+ ));
+ }));
+
+ app.put<{ Params: { projectId: string; conversationId: string } }>("/api/collab/projects/:projectId/tasks/:conversationId/sharing", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; conversationId: string };
+ const input = TaskSharingSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.setTaskSharing(
+ ProjectIdSchema.parse(params.projectId),
+ ConversationIdSchema.parse(params.conversationId),
+ input.shared
+ ));
+ }));
+
+ app.get<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/links", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.getLinks(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.put<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/links", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = LinksSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.saveLinks(projectId, input));
+ }));
+
+ app.delete<{ Params: { projectId: string } }>("/api/collab/projects/:projectId", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.deleteProject(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ // One PATCH per project: `name` renames it for every member (owner only, enforced by the cloud), `joinMode` says
+ // how a link lets people in. Members, invite links, join requests and roles live below.
+ app.patch<{ Params: { projectId: string } }>("/api/collab/projects/:projectId", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const body = request.body ?? {};
+ if (typeof (body as { name?: unknown }).name === "string") {
+ const input = RenameProjectSchema.parse(body);
+ return reply.send(await options.collab.renameProject(projectId, input.name));
+ }
+ // 项目指令由所有者与管理员编辑(云端判定权限),后端把内容缓存到协作侧自己的文件,项目里的任务随即按新指令执行。
+ if (typeof (body as { instructions?: unknown }).instructions === "string") {
+ const input = InstructionsSchema.parse(body);
+ return reply.send(await options.collab.updateInstructions(projectId, input.instructions, input.directory));
+ }
+ const input = UpdateProjectSchema.parse(body);
+ return reply.send(await options.collab.setJoinMode(projectId, input.joinMode));
+ }));
+
+ // 项目配置的知识库:关联对本项目全体成员开放,解除由云端判定(关联人自己或所有者、管理员)。
+ app.get<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/knowledge", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.knowledge(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.post<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/knowledge", guard, withErrorEnvelope(async (request, reply) => {
+ const projectId = ProjectIdSchema.parse((request.params as { projectId: string }).projectId);
+ const input = KnowledgeLinkSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.addKnowledge(projectId, input.baseId));
+ }));
+
+ app.delete<{ Params: { projectId: string; baseId: string } }>("/api/collab/projects/:projectId/knowledge/:baseId", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; baseId: string };
+ return reply.send(await options.collab.removeKnowledge(
+ ProjectIdSchema.parse(params.projectId),
+ BaseIdSchema.parse(params.baseId)
+ ));
+ }));
+
+ app.get<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/members", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.listMembers(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.post<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/invite", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.createInvite(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.post<{ Params: { projectId: string } }>("/api/collab/projects/:projectId/leave", guard, withErrorEnvelope(async (request, reply) =>
+ reply.send(await options.collab.leaveProject(ProjectIdSchema.parse((request.params as { projectId: string }).projectId)))));
+
+ app.post<{ Params: { projectId: string; userId: string } }>("/api/collab/projects/:projectId/requests/:userId/approve", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; userId: string };
+ return reply.send(await options.collab.approveRequest(ProjectIdSchema.parse(params.projectId), UserIdSchema.parse(params.userId)));
+ }));
+
+ app.delete<{ Params: { projectId: string; userId: string } }>("/api/collab/projects/:projectId/requests/:userId", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; userId: string };
+ return reply.send(await options.collab.rejectRequest(ProjectIdSchema.parse(params.projectId), UserIdSchema.parse(params.userId)));
+ }));
+
+ app.patch<{ Params: { projectId: string; userId: string } }>("/api/collab/projects/:projectId/members/:userId", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; userId: string };
+ const input = MemberRoleSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.setMemberRole(ProjectIdSchema.parse(params.projectId), UserIdSchema.parse(params.userId), input.role));
+ }));
+
+ app.delete<{ Params: { projectId: string; userId: string } }>("/api/collab/projects/:projectId/members/:userId", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; userId: string };
+ return reply.send(await options.collab.removeMember(ProjectIdSchema.parse(params.projectId), UserIdSchema.parse(params.userId)));
+ }));
+
+ // Joining starts from a pasted link: preview what it opens, then join or apply.
+ app.post("/api/collab/invites/preview", guard, withErrorEnvelope(async (request, reply) => {
+ const input = PreviewInviteSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.previewInvite(input.reference));
+ }));
+
+ app.post("/api/collab/invites/join", guard, withErrorEnvelope(async (request, reply) => {
+ const input = JoinSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.joinProject(input.reference, input.directory, input.nickname));
+ }));
+
+ app.delete<{ Params: { projectId: string; sessionId: string } }>("/api/collab/projects/:projectId/sessions/:sessionId", guard, withErrorEnvelope(async (request, reply) => {
+ const params = request.params as { projectId: string; sessionId: string };
+ return reply.send(await options.collab.removeSession(ProjectIdSchema.parse(params.projectId), ProjectIdSchema.parse(params.sessionId)));
+ }));
+
+ // Opening a board syncs first, so a task finished a moment ago is already in its project's session list.
+ // `tasks` keeps it to Memmy's own tasks, which needs no agent scan and returns in milliseconds.
+ app.post("/api/collab/sync", guard, withErrorEnvelope(async (request, reply) => {
+ const input = SyncSchema.parse(request.body ?? {});
+ return reply.send(input.tasks
+ ? await options.collab.syncProjectTasks(input.projectId)
+ : await options.collab.syncLinkedSessions());
+ }));
+
+ app.post("/api/collab/local-sessions", guard, withErrorEnvelope(async (request, reply) => {
+ const input = LocalSessionsSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.listLocalSessions(input));
+ }));
+
+ // 在其他 Agent 中使用协作项目的授权:设置页、授权弹窗与看板的询问都读写这一份状态。
+ app.get("/api/collab/agent-access", guard, withErrorEnvelope(async (_request, reply) => {
+ if (!options.agentAccess) throw new CollabError("not_found", "这个版本不支持协作项目授权");
+ return reply.send(await options.agentAccess.view());
+ }));
+
+ app.put("/api/collab/agent-access", guard, withErrorEnvelope(async (request, reply) => {
+ if (!options.agentAccess) throw new CollabError("not_found", "这个版本不支持协作项目授权");
+ const input = AgentAccessSchema.parse(request.body ?? {});
+ const result = await options.agentAccess.setGranted(input.granted);
+ // 状态与逐个 Agent 的安装结果平铺在同一个回应里:界面一次拿到,失败的可重试。
+ return reply.send({ ...result.view, results: result.results });
+ }));
+
+ // 已授权但没装上(当时 Agent 不在、或装失败)时重新装一次,可只装指定几个。
+ app.post("/api/collab/agent-access/install", guard, withErrorEnvelope(async (request, reply) => {
+ if (!options.agentAccess) throw new CollabError("not_found", "这个版本不支持协作项目授权");
+ const input = AgentAccessInstallSchema.parse(request.body ?? {});
+ const result = await options.agentAccess.install(input.sourceIds);
+ return reply.send({ ...result.view, results: result.results });
+ }));
+
+ // 记下已经在项目里询问过一次:选「暂不安装」也算,之后不再主动询问。
+ app.post("/api/collab/agent-access/asked", guard, withErrorEnvelope(async (_request, reply) => {
+ if (!options.agentAccess) throw new CollabError("not_found", "这个版本不支持协作项目授权");
+ await options.agentAccess.markAsked();
+ return reply.send(await options.agentAccess.view());
+ }));
+
+ // 设置里逐个开关:关掉不再读取、卸载组件;打开时若已授权就装回去。
+ app.put<{ Params: { sourceId: string } }>("/api/collab/agent-access/agents/:sourceId", guard, withErrorEnvelope(async (request, reply) => {
+ if (!options.agentAccess) throw new CollabError("not_found", "这个版本不支持协作项目授权");
+ const input = AgentEnabledSchema.parse(request.body ?? {});
+ const result = await options.agentAccess.setAgentEnabled(
+ AgentSourceSchema.parse((request.params as { sourceId: string }).sourceId),
+ input.enabled
+ );
+ return reply.send({ ...result.view, results: result.results });
+ }));
+
+ app.get("/api/collab/sessions/search", guard, withErrorEnvelope(async (request, reply) => {
+ const input = SearchSchema.parse(request.query ?? {});
+ return reply.send(await options.collab.searchSessions({
+ ...(input.q === undefined ? {} : { query: input.q }),
+ ...(input.member === undefined ? {} : { member: input.member }),
+ ...(input.project === undefined ? {} : { project: input.project }),
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
+ ...(input.since === undefined ? {} : { since: input.since, sinceMs: sinceWindowMs(input.since) ?? undefined })
+ }));
+ }));
+
+ app.post("/api/collab/sessions/read", guard, withErrorEnvelope(async (request, reply) => {
+ const input = ReadSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.readSession(input.reference, input.view));
+ }));
+
+ app.post("/api/collab/knowledge/search", guard, withErrorEnvelope(async (request, reply) => {
+ const input = SearchKnowledgeSchema.parse(request.body ?? {});
+ if (!options.recallProjectKnowledge) throw new CollabError("internal", "知识库服务未就绪");
+ if (!input.project && !input.sourceId) throw new CollabError("invalid_argument", "无法识别当前会话,请用 --project 指定项目名称");
+ const projects = input.sourceId && input.conversationId
+ ? await options.collab.projectsForAgentSession(input.sourceId, input.conversationId)
+ : (await options.collab.listProjects()).projects;
+ const matches = input.project
+ ? matchProject(projects, input.project)
+ : projects;
+ if (!matches.length) throw new CollabError("not_found", missingProjectMessage(input.project, Boolean(input.sourceId)));
+ if (matches.length > 1) {
+ throw new CollabError(
+ "conflict",
+ `当前会话关联多个项目,请用 --project 指定:${matches.map((project) => `${project.name} #${project.id.slice(0, 8)}`).join("、")}`
+ );
+ }
+ const project = matches[0]!;
+ const result = await options.recallProjectKnowledge(input.query, project.id);
+ return reply.send({ project: { id: project.id, name: project.name }, ...result });
+ }));
+
+ // 添加一个用户自己的 Agent:只把 memmy-project 装进它的技能目录,回复就是 `memmy-project agent connect` 打印的文字。
+ app.post("/api/collab/agents/connect", guard, withErrorEnvelope(async (request, reply) => {
+ const input = ConnectAgentSchema.parse(request.body ?? {});
+ try {
+ const result = await connectCollabAgent({
+ name: input.name,
+ skillDirectory: input.skillDirectory
+ });
+ return reply.send({ text: result.text, sourceId: result.sourceId });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "没有添加这个 Agent。";
+ return reply.send({ text: message });
+ }
+ }));
+
+ app.post("/api/collab/agents/remove", guard, withErrorEnvelope(async (request, reply) => {
+ const input = RemoveAgentSchema.parse(request.body ?? {});
+ return reply.send({ text: await removeCollabAgent(input.name) });
+ }));
+
+ app.post("/api/collab/sessions/add", guard, withErrorEnvelope(async (request, reply) => {
+ const input = AddSessionSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.addCurrentSession({
+ ...(input.project === undefined ? {} : { project: input.project }),
+ ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
+ ...(input.hint === undefined ? {} : { hint: input.hint }),
+ ...(input.sourceId === undefined ? {} : { sourceId: input.sourceId }),
+ ...(input.conversationId === undefined ? {} : { conversationId: input.conversationId }),
+ ...(input.submission === undefined ? {} : { submission: input.submission })
+ }));
+ }));
+
+ // One Memmy task shares or stops sharing itself with its own project. The reply is the text `session share` prints.
+ app.post("/api/collab/sessions/share", guard, withErrorEnvelope(async (request, reply) => {
+ const input = ShareCurrentTaskSchema.parse(request.body ?? {});
+ return reply.send(await options.collab.shareCurrentTask({
+ conversationId: input.conversationId,
+ shared: input.shared,
+ ...(input.project === undefined ? {} : { project: input.project })
+ }));
+ }));
+}
+
+/** Why a knowledge search found no project: no project was named, or the named one is not linked to this session. */
+/**
+ * 按 --project 的值找项目:先认 id(含短前缀),再认完整名称,最后才按前缀试一次。
+ * 同名项目只能靠 id 分开,所以 id 认得的排在名称前面。
+ */
+function matchProject(projects: readonly T[], want: string): T[] {
+ const value = want.trim();
+ if (!value) return [...projects];
+ const byId = projects.filter((project) => project.id === value);
+ if (byId.length) return byId;
+ const byName = projects.filter((project) => project.name === value);
+ if (byName.length) return byName;
+ return projects.filter((project) => project.id.startsWith(value));
+}
+
+function missingProjectMessage(project: string | undefined, sessionKnown: boolean): string {
+ if (!sessionKnown) return "没有该项目,或你不是项目成员";
+ if (project) return `当前会话未关联项目「${project}」`;
+ return "当前会话没有关联任何协作项目,检索不到项目知识库;可以先用 memmy-project session add 把当前任务加入项目,或用 --project 指定项目。";
+}
diff --git a/App/backend/src/adapters/inbound/local-api/routes/projects.ts b/App/backend/src/adapters/inbound/local-api/routes/projects.ts
new file mode 100644
index 000000000..d1c02f46a
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/routes/projects.ts
@@ -0,0 +1,52 @@
+/** Local project utilities: the managed folder a project without a chosen directory runs in, and project instructions. */
+import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { withErrorEnvelope } from "../../../../services/error-envelope.js";
+import { MAX_PROJECT_INSTRUCTIONS_CHARS } from "@memmy/local-api-contracts";
+import type { ProjectDirectoryService } from "../../../../services/project-directory-service.js";
+import type { ProjectInstructionsService } from "../../../../services/project-instructions-service.js";
+
+export interface RegisterProjectRoutesOptions {
+ /** 按名称创建项目时用的托管目录;未提供时只注册项目指令接口。 */
+ projectDirectory?: ProjectDirectoryService;
+ /** 本机项目的项目指令:只属于这台电脑上的文件夹,协作项目有自己的一套接口。 */
+ projectInstructions?: ProjectInstructionsService;
+ authenticateRuntimeToken: (request: FastifyRequest, reply: FastifyReply) => Promise;
+}
+
+const PrepareDirectorySchema = z.object({
+ name: z.string().trim().min(1, "请填写项目名称").max(60, "项目名称过长")
+}).strict();
+/** 目录是项目任务所在位置:绝对路径,且长度与各平台路径上限一致。 */
+const DirectorySchema = z.string().trim().min(1).max(4_096).refine((value) => value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value), "项目目录需为绝对路径");
+const ReadInstructionsSchema = z.object({ directory: DirectorySchema }).strict();
+const SaveInstructionsSchema = z.object({
+ directory: DirectorySchema,
+ text: z.string().max(MAX_PROJECT_INSTRUCTIONS_CHARS * 4).default("")
+}).strict();
+
+/** Registers the local project routes. */
+export function registerProjectRoutes(app: FastifyInstance, options: RegisterProjectRoutesOptions): void {
+ // A project created by name alone still needs a working directory: this is where it gets one.
+ if (options.projectDirectory) {
+ app.post("/api/projects/working-directory", { preHandler: options.authenticateRuntimeToken }, withErrorEnvelope(async (request, reply) => {
+ const input = PrepareDirectorySchema.parse(request.body ?? {});
+ return reply.send(await options.projectDirectory!.prepareManagedDirectory(input.name));
+ }));
+ }
+
+ if (!options.projectInstructions) return;
+ // 看板打开项目配置时读当前生效的指令;协作项目的指令由云端同步到同一份存储。
+ app.get("/api/projects/instructions", { preHandler: options.authenticateRuntimeToken }, withErrorEnvelope(async (request, reply) => {
+ const input = ReadInstructionsSchema.parse(request.query ?? {});
+ return reply.send(await options.projectInstructions!.read(input.directory));
+ }));
+ // 只有本机项目在这里保存;协作项目走云端的项目接口,再由后端同步到本机。
+ app.put("/api/projects/instructions", { preHandler: options.authenticateRuntimeToken }, withErrorEnvelope(async (request, reply) => {
+ const input = SaveInstructionsSchema.parse(request.body ?? {});
+ if ([...input.text.trim()].length > MAX_PROJECT_INSTRUCTIONS_CHARS) {
+ return reply.status(400).send({ error: { code: "invalid_argument", message: `背景与规范不超过 ${MAX_PROJECT_INSTRUCTIONS_CHARS} 字` } });
+ }
+ return reply.send(await options.projectInstructions!.saveLocal(input.directory, input.text));
+ }));
+}
diff --git a/App/backend/src/adapters/inbound/local-api/server.ts b/App/backend/src/adapters/inbound/local-api/server.ts
index 31f561faf..7a59b7004 100644
--- a/App/backend/src/adapters/inbound/local-api/server.ts
+++ b/App/backend/src/adapters/inbound/local-api/server.ts
@@ -2,11 +2,15 @@
import { SseEventSchema, type SseEvent } from "@memmy/local-api-contracts";
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
import { randomUUID } from "node:crypto";
-import type { ManagedKnowledgeOptions } from "@memmy/knowledge";
+import { KnowledgeError, ManagedKnowledgeClient, parseEvidence, type ManagedKnowledgeOptions } from "@memmy/knowledge";
import { registerKnowledgeRoutes } from "@memmy/knowledge/routes";
import type { PermissionManager } from "../../../permission/index.js";
import type { BackendServices } from "../../../services/index.js";
+import type { CollabService } from "../../../services/collab-service.js";
+import type { CollabAgentAccessService } from "../../../services/collab-agent-access-service.js";
+import type { ProjectDirectoryService } from "../../../services/project-directory-service.js";
import { registerAccountRoutes } from "./routes/account.js";
+import { registerCollabRoutes } from "./routes/collab.js";
import { registerTokenQuotaRoutes } from "./routes/token-quota.js";
import { registerAppConfigRoutes } from "./routes/app-config.js";
import { registerAgentSourceRoutes } from "./routes/agent-sources.js";
@@ -18,6 +22,7 @@ import { registerComposioMcpRoutes } from "./routes/composio-mcp.js";
import { registerIntegrationRoutes } from "./routes/integrations.js";
import { registerLocalDataRoutes } from "./routes/local-data.js";
import { registerOnboardingInsightRoutes } from "./routes/onboarding-insight.js";
+import { registerProjectRoutes } from "./routes/projects.js";
import { registerPluginRoutes } from "./routes/plugins.js";
import { registerPluginMcpRoutes } from "./routes/plugin-mcp.js";
@@ -32,6 +37,12 @@ const FILE_ORIGIN = "file://";
export interface CreateLocalApiServerOptions {
knowledge?: ManagedKnowledgeOptions;
+ /** Online projects; absent in tests that do not exercise them. */
+ collab?: CollabService;
+ /** 「在其他 Agent 中使用协作项目」的授权状态;absent 时那几个接口不可用。 */
+ collabAgentAccess?: CollabAgentAccessService;
+ /** The managed folder a project created by name alone runs its tasks in. */
+ projectDirectory?: ProjectDirectoryService;
permissionManager: PermissionManager;
services: BackendServices;
/** Configured agent timezone. Renderer headers are used only when absent. */
@@ -75,7 +86,13 @@ export function createLocalApiServer(options: CreateLocalApiServerOptions): Fast
});
if (options.knowledge) {
- registerKnowledgeRoutes(app, { ...options.knowledge, authenticate: authenticateRuntimeToken });
+ registerKnowledgeRoutes(app, {
+ ...options.knowledge,
+ authenticate: authenticateRuntimeToken,
+ // 会话目录属于某个协作项目时,项目关联的知识库与该成员自己的库一起检索。
+ projectForWorkspace: async (workspace) =>
+ (await options.collab?.cloudProjectForDirectory(workspace)) ?? null,
+ });
}
app.addHook("onRequest", async (request, reply) => {
@@ -152,6 +169,22 @@ export function createLocalApiServer(options: CreateLocalApiServerOptions): Fast
localData: options.services.localData,
authenticateRuntimeToken
});
+ if (options.collab) {
+ const knowledge = options.knowledge ? new ManagedKnowledgeClient(options.knowledge) : null;
+ registerCollabRoutes(app, {
+ collab: options.collab, authenticateRuntimeToken,
+ ...(options.collabAgentAccess ? { agentAccess: options.collabAgentAccess } : {}),
+ ...(knowledge ? { recallProjectKnowledge: (query: string, projectId: string) => recallProjectBases(knowledge, query, projectId) } : {})
+ });
+ }
+ // 项目指令与托管目录都是项目自己的接口,任一需要时都注册:指令不依赖托管目录。
+ if (options.projectDirectory || options.services.projectInstructions) {
+ registerProjectRoutes(app, {
+ projectDirectory: options.projectDirectory,
+ projectInstructions: options.services.projectInstructions,
+ authenticateRuntimeToken
+ });
+ }
registerByokTokenUsageRoutes(app, {
byokTokenUsage: options.services.byokTokenUsage,
authenticateRuntimeToken
@@ -253,6 +286,29 @@ async function isAuthorized(request: FastifyRequest, permissionManager: Permissi
return typeof token === "string" && (await permissionManager.verifyRuntimeToken(token));
}
+/**
+ * 项目知识库检索:只要项目关联的知识库,不把个人知识库的个人资料混进项目资料里。
+ * 云端还不认识 `projectOnly` 时(HTTP 400 参数无效)退回按项目检索的旧范围,并在结果里标明范围更宽,
+ * 让调用方、进而让 Agent 知道自己拿到的可能不全是项目资料。
+ */
+async function recallProjectBases(
+ knowledge: ManagedKnowledgeClient,
+ query: string,
+ projectId: string
+): Promise<{ enabled: boolean; evidence: unknown[]; projectOnly: boolean }> {
+ const read = (data: unknown) => {
+ const result = data && typeof data === "object" ? data as Record : {};
+ return { enabled: result.enabled === true, evidence: parseEvidence(result.evidence) };
+ };
+ try {
+ return { ...read(await knowledge.request("/recall", "POST", { query, projectId, projectOnly: true })), projectOnly: true };
+ } catch (error) {
+ // Only a rejected parameter means an older cloud; auth, timeout and service errors must reach the caller.
+ if (!(error instanceof KnowledgeError) || !error.message.startsWith("[HTTP 400]")) throw error;
+ return { ...read(await knowledge.request("/recall", "POST", { query, projectId })), projectOnly: false };
+ }
+}
+
function applyCorsHeaders(
reply: FastifyReply,
origin: string | undefined,
diff --git a/App/backend/src/adapters/inbound/local-api/tests/account-routes.test.ts b/App/backend/src/adapters/inbound/local-api/tests/account-routes.test.ts
index f8557ffbf..64b74c9da 100644
--- a/App/backend/src/adapters/inbound/local-api/tests/account-routes.test.ts
+++ b/App/backend/src/adapters/inbound/local-api/tests/account-routes.test.ts
@@ -106,34 +106,6 @@ describe("account local api routes", () => {
]);
});
- it("forwards lottery reward lookup and acknowledgement through AccountService", async () => {
- const calls: unknown[] = [];
- app = createServer({
- account: {
- async getLotteryReward() {
- calls.push("get");
- return { hasReward: true as const, drawId: "1", tokenAmount: 500_000 };
- },
- async ackLotteryReward(input: unknown) {
- calls.push({ ack: input });
- return { ok: true };
- }
- }
- });
-
- const reward = await app.inject({
- method: "GET",
- url: "/api/account/lottery/reward",
- headers: { "x-memmy-local-token": "test-token" }
- });
- const ack = await injectJson("POST", "/api/account/lottery/reward/ack", { drawId: "1" });
-
- expect(reward.statusCode).toBe(200);
- expect(reward.json()).toEqual({ hasReward: true, drawId: "1", tokenAmount: 500_000 });
- expect(ack.json()).toEqual({ ok: true });
- expect(calls).toEqual(["get", { ack: { drawId: "1" } }]);
- });
-
it("lists avatars and stores the selected avatar behind the runtime token", async () => {
const calls: string[] = [];
app = createServer({
diff --git a/App/backend/src/adapters/inbound/local-api/tests/collab-agent-access-routes.test.ts b/App/backend/src/adapters/inbound/local-api/tests/collab-agent-access-routes.test.ts
new file mode 100644
index 000000000..a6c15909d
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/tests/collab-agent-access-routes.test.ts
@@ -0,0 +1,93 @@
+/** Collab agent access routes: the authorization the board and settings read and change. */
+import Fastify, { type FastifyInstance } from "fastify";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { CollabAgentAccessService } from "../../../../services/collab-agent-access-service.js";
+import type { CollabService } from "../../../../services/collab-service.js";
+import { registerCollabRoutes } from "../routes/collab.js";
+
+const VIEW = {
+ granted: false,
+ askedInProject: false,
+ agents: [{ sourceId: "cursor", name: "Cursor", available: true, enabled: true, installed: false, added: false }]
+};
+
+let app: FastifyInstance | undefined;
+afterEach(async () => {
+ await app?.close();
+ app = undefined;
+});
+
+function createApp() {
+ const access = {
+ view: vi.fn(async () => VIEW),
+ setGranted: vi.fn(async (granted: boolean) => ({
+ view: { ...VIEW, granted },
+ results: granted ? [{ sourceId: "cursor", name: "Cursor", ok: true }] : []
+ })),
+ install: vi.fn(async () => ({ view: VIEW, results: [] })),
+ markAsked: vi.fn(async () => ({ ...VIEW, askedInProject: true })),
+ setAgentEnabled: vi.fn(async (sourceId: string, enabled: boolean) => ({
+ view: {
+ ...VIEW,
+ agents: [{ ...VIEW.agents[0], enabled }]
+ },
+ results: []
+ })),
+ read: vi.fn(),
+ readableSourceIds: vi.fn()
+ };
+ app = Fastify();
+ registerCollabRoutes(app, {
+ collab: {} as unknown as CollabService,
+ agentAccess: access as unknown as CollabAgentAccessService,
+ authenticateRuntimeToken: async () => undefined
+ });
+ return access;
+}
+
+describe("collab agent access routes", () => {
+ it("reads the current authorization", async () => {
+ createApp();
+ const response = await app!.inject({ method: "GET", url: "/api/collab/agent-access" });
+ expect(response.statusCode).toBe(200);
+ expect(response.json()).toEqual(VIEW);
+ });
+
+ it("grants and returns the per-agent install results", async () => {
+ const access = createApp();
+ const response = await app!.inject({ method: "PUT", url: "/api/collab/agent-access", payload: { granted: true } });
+ expect(access.setGranted).toHaveBeenCalledWith(true);
+ expect(response.json()).toMatchObject({ granted: true, results: [{ sourceId: "cursor", ok: true }] });
+ });
+
+ it("records the in-project question and toggles one agent", async () => {
+ const access = createApp();
+ await app!.inject({ method: "POST", url: "/api/collab/agent-access/asked" });
+ expect(access.markAsked).toHaveBeenCalledOnce();
+
+ const toggled = await app!.inject({
+ method: "PUT",
+ url: "/api/collab/agent-access/agents/cursor",
+ payload: { enabled: false }
+ });
+ expect(access.setAgentEnabled).toHaveBeenCalledWith("cursor", false);
+ expect(toggled.json().agents[0].enabled).toBe(false);
+ });
+
+ it("rejects an agent id that is not a source id", async () => {
+ const access = createApp();
+ const response = await app!.inject({
+ method: "PUT",
+ url: `/api/collab/agent-access/agents/${encodeURIComponent("../etc/passwd")}`,
+ payload: { enabled: false }
+ });
+ expect(response.statusCode).toBe(400);
+ expect(access.setAgentEnabled).not.toHaveBeenCalled();
+ });
+
+ it("installs again only for the agents that failed", async () => {
+ const access = createApp();
+ await app!.inject({ method: "POST", url: "/api/collab/agent-access/install", payload: { sourceIds: ["codex"] } });
+ expect(access.install).toHaveBeenCalledWith(["codex"]);
+ });
+});
diff --git a/App/backend/src/adapters/inbound/local-api/tests/collab-knowledge-search.test.ts b/App/backend/src/adapters/inbound/local-api/tests/collab-knowledge-search.test.ts
new file mode 100644
index 000000000..dc0a7597e
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/tests/collab-knowledge-search.test.ts
@@ -0,0 +1,105 @@
+/** Collab knowledge search: a linked agent session picks the project, and an ambiguous match is never guessed. */
+import Fastify, { type FastifyInstance } from "fastify";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { CollabService } from "../../../../services/collab-service.js";
+import { registerCollabRoutes } from "../routes/collab.js";
+
+const ONE = { id: "p-1", name: "MemOS" };
+const TWO = { id: "p-2", name: "产品" };
+
+let app: FastifyInstance | undefined;
+afterEach(async () => {
+ await app?.close();
+ app = undefined;
+});
+
+function createApp(projects: unknown[], recall: ReturnType) {
+ const projectsForAgentSession = vi.fn().mockResolvedValue(projects);
+ app = Fastify();
+ registerCollabRoutes(app, {
+ collab: { projectsForAgentSession } as unknown as CollabService,
+ authenticateRuntimeToken: async () => undefined,
+ recallProjectKnowledge: recall as unknown as (query: string, projectId: string) => Promise<{ enabled: boolean; evidence: unknown[] }>
+ });
+ return projectsForAgentSession;
+}
+
+describe("collab knowledge search", () => {
+ it("searches the project the session is linked to", async () => {
+ const recall = vi.fn().mockResolvedValue({ enabled: true, evidence: [{ title: "需求", content: "模板" }] });
+ const projectsForAgentSession = createApp([ONE], recall);
+
+ const response = await app!.inject({
+ method: "POST",
+ url: "/api/collab/knowledge/search",
+ payload: { query: "属性记忆模板", sourceId: "codex", conversationId: "thread-1" }
+ });
+
+ expect(response.statusCode).toBe(200);
+ expect(projectsForAgentSession).toHaveBeenCalledWith("codex", "thread-1");
+ expect(recall).toHaveBeenCalledWith("属性记忆模板", "p-1");
+ expect(response.json()).toMatchObject({ project: ONE, enabled: true, evidence: [{ title: "需求" }] });
+ });
+
+ it("refuses to guess when the session is linked to several projects", async () => {
+ const recall = vi.fn();
+ createApp([ONE, TWO], recall);
+ const payload = { query: "属性记忆模板", sourceId: "codex", conversationId: "thread-1" };
+
+ const ambiguous = await app!.inject({ method: "POST", url: "/api/collab/knowledge/search", payload });
+
+ expect(ambiguous.statusCode).toBe(409);
+ expect(ambiguous.json()).toMatchObject({ error: { code: "conflict" } });
+ // 同名项目只能靠短码区分,所以提示里两个都带上 id 前 8 位。
+ expect(ambiguous.json().error.message).toContain("MemOS #p-1、产品 #p-2");
+ expect(recall).not.toHaveBeenCalled();
+
+ const selected = await app!.inject({ method: "POST", url: "/api/collab/knowledge/search", payload: { ...payload, project: "MemOS" } });
+ expect(selected.statusCode).toBe(200);
+ expect(recall).toHaveBeenCalledWith("属性记忆模板", "p-1");
+
+ // --project 直接给 id 也认:这是同名项目唯一可靠的指定方式。
+ const byId = await app!.inject({ method: "POST", url: "/api/collab/knowledge/search", payload: { ...payload, project: "p-2" } });
+ expect(byId.statusCode).toBe(200);
+ expect(recall).toHaveBeenCalledWith("属性记忆模板", "p-2");
+ });
+
+ it("turns away a project the session is not linked to and an incomplete identity", async () => {
+ const recall = vi.fn();
+ createApp([ONE], recall);
+
+ const wrong = await app!.inject({
+ method: "POST",
+ url: "/api/collab/knowledge/search",
+ payload: { query: "模板", sourceId: "codex", conversationId: "thread-1", project: "其他" }
+ });
+ const halfIdentity = await app!.inject({
+ method: "POST",
+ url: "/api/collab/knowledge/search",
+ payload: { query: "模板", sourceId: "codex" }
+ });
+ const noTarget = await app!.inject({ method: "POST", url: "/api/collab/knowledge/search", payload: { query: "模板" } });
+
+ expect(wrong.statusCode).toBe(404);
+ expect(wrong.json()).toMatchObject({ error: { message: "当前会话未关联项目「其他」" } });
+ expect(halfIdentity.statusCode).toBe(400);
+ expect(noTarget.statusCode).toBe(400);
+ expect(recall).not.toHaveBeenCalled();
+ });
+
+ it("tells a session with no project how to link one", async () => {
+ const recall = vi.fn();
+ createApp([], recall);
+
+ const response = await app!.inject({
+ method: "POST",
+ url: "/api/collab/knowledge/search",
+ payload: { query: "模板", sourceId: "codex", conversationId: "thread-1" }
+ });
+
+ expect(response.statusCode).toBe(404);
+ expect(response.json().error.message).toContain("没有关联任何协作项目");
+ expect(response.json().error.message).toContain("memmy-project session add");
+ expect(recall).not.toHaveBeenCalled();
+ });
+});
diff --git a/App/backend/src/adapters/inbound/local-api/tests/collab-knowledge-wiring.test.ts b/App/backend/src/adapters/inbound/local-api/tests/collab-knowledge-wiring.test.ts
new file mode 100644
index 000000000..b3acbbfea
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/tests/collab-knowledge-wiring.test.ts
@@ -0,0 +1,104 @@
+/** Collab knowledge search wiring: the local route asks the cloud for project-only recall and returns its evidence. */
+import { createServer as createHttpServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import type { FastifyInstance } from "fastify";
+import { afterEach, describe, expect, it } from "vitest";
+import type { PermissionManager } from "../../../../permission/index.js";
+import type { CollabService } from "../../../../services/collab-service.js";
+import { createProgressBus } from "../../../../services/progress-bus.js";
+import type { BackendServices } from "../../../../services/index.js";
+import { createLocalApiServer } from "../server.js";
+
+const EVIDENCE = { enabled: true, evidence: [{ id: "source-1", title: "属性记忆模板管理 API 需求", content: "模板接口说明" }] };
+
+let app: FastifyInstance | undefined;
+let stub: Server | undefined;
+
+afterEach(async () => {
+ await app?.close();
+ app = undefined;
+ await new Promise((resolve) => (stub ? stub.close(() => resolve()) : resolve()));
+ stub = undefined;
+});
+
+/** A cloud stub that records every recall request and answers with `reply`. */
+async function startCloud(reply: (body: Record) => { status: number; payload: unknown }) {
+ const received: Array<{ path: string; body: Record }> = [];
+ stub = createHttpServer((request, response) => {
+ let raw = "";
+ request.on("data", (chunk) => { raw += String(chunk); });
+ request.on("end", () => {
+ const body = raw ? JSON.parse(raw) as Record : {};
+ received.push({ path: request.url ?? "", body });
+ const { status, payload } = reply(body);
+ response.writeHead(status, { "content-type": "application/json" });
+ response.end(JSON.stringify(payload));
+ });
+ });
+ await new Promise((resolve) => stub!.listen(0, "127.0.0.1", resolve));
+ const { port } = stub.address() as AddressInfo;
+ app = createLocalApiServer({
+ knowledge: { baseUrl: `http://127.0.0.1:${port}`, getSession: () => ({ accountId: "u-1", credential: "credential" }) },
+ collab: { projectsForAgentSession: async () => [{ id: "p-1", name: "MemOS" }] } as unknown as CollabService,
+ permissionManager: { verifyRuntimeToken: async () => true } as PermissionManager,
+ composioMcpToken: "mcp-token",
+ services: {
+ bootstrap: { async getBootstrap() { throw new Error("bootstrap not used"); } },
+ progressBus: createProgressBus()
+ } as BackendServices
+ });
+ return received;
+}
+
+function searchKnowledge() {
+ return app!.inject({
+ method: "POST",
+ url: "/api/collab/knowledge/search",
+ headers: { "x-memmy-local-token": "runtime-token" },
+ payload: { query: "属性记忆模板管理 API", sourceId: "codex", conversationId: "thread-1" }
+ });
+}
+
+describe("collab knowledge search wiring", () => {
+ it("asks the cloud for project-only recall and returns its evidence", async () => {
+ const received = await startCloud(() => ({ status: 200, payload: { code: 0, data: EVIDENCE } }));
+
+ const response = await searchKnowledge();
+
+ expect(response.statusCode).toBe(200);
+ expect(received.map((call) => call.path)).toEqual(["/api/knowledge/recall"]);
+ // The project's own bases are the only scope: personal bases must not leak into a project answer.
+ expect(received[0]!.body).toEqual({ query: "属性记忆模板管理 API", projectId: "p-1", projectOnly: true });
+ expect(response.json()).toMatchObject({
+ project: { id: "p-1", name: "MemOS" },
+ enabled: true,
+ projectOnly: true,
+ evidence: [{ title: "属性记忆模板管理 API 需求", content: "模板接口说明" }]
+ });
+ });
+
+ it("falls back to the project's older scope when the cloud rejects the parameter", async () => {
+ const received = await startCloud((body) => body.projectOnly === true
+ ? { status: 400, payload: { code: 400, data: null, message: "知识库请求参数无效" } }
+ : { status: 200, payload: { code: 0, data: EVIDENCE } });
+
+ const response = await searchKnowledge();
+
+ expect(response.statusCode).toBe(200);
+ expect(received.map((call) => call.body)).toEqual([
+ { query: "属性记忆模板管理 API", projectId: "p-1", projectOnly: true },
+ { query: "属性记忆模板管理 API", projectId: "p-1" }
+ ]);
+ // The caller has to know the answer may include personal bases, not only the project's.
+ expect(response.json()).toMatchObject({ projectOnly: false, evidence: [{ title: "属性记忆模板管理 API 需求" }] });
+ });
+
+ it("keeps real failures instead of retrying them as a wider scope", async () => {
+ const received = await startCloud(() => ({ status: 503, payload: { code: 503, data: null, message: "服务不可用" } }));
+
+ const response = await searchKnowledge();
+
+ expect(response.statusCode).toBeGreaterThanOrEqual(500);
+ expect(received).toHaveLength(1);
+ });
+});
diff --git a/App/backend/src/adapters/inbound/local-api/tests/collab-member-routes.test.ts b/App/backend/src/adapters/inbound/local-api/tests/collab-member-routes.test.ts
new file mode 100644
index 000000000..8497c8e55
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/tests/collab-member-routes.test.ts
@@ -0,0 +1,99 @@
+/** Collab member routes: a real Memmy account id is a 19-digit snowflake, so every :userId route must accept it. */
+import Fastify, { type FastifyInstance } from "fastify";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { CollabService } from "../../../../services/collab-service.js";
+import { registerCollabRoutes } from "../routes/collab.js";
+
+/** What `~/.memmy/config.yaml` holds for a signed-in account. */
+const ACCOUNT_ID = "2102247370314383361";
+const MEMBER = { userId: ACCOUNT_ID, name: "元气桂花", role: "member", mine: false, joinedAt: null };
+
+let app: FastifyInstance | undefined;
+afterEach(async () => {
+ await app?.close();
+ app = undefined;
+});
+
+function createApp() {
+ const calls: string[] = [];
+ const stub = {
+ approveRequest: vi.fn(async (_projectId: string, userId: string) => {
+ calls.push(`approve:${userId}`);
+ return { ...MEMBER, userId };
+ }),
+ rejectRequest: vi.fn(async (_projectId: string, userId: string) => {
+ calls.push(`reject:${userId}`);
+ return { ok: true };
+ }),
+ setMemberRole: vi.fn(async (_projectId: string, userId: string, _role: string) => {
+ calls.push(`role:${userId}`);
+ return { ...MEMBER, userId };
+ }),
+ removeMember: vi.fn(async (_projectId: string, userId: string) => {
+ calls.push(`remove:${userId}`);
+ return { ok: true };
+ })
+ };
+ app = Fastify();
+ registerCollabRoutes(app, {
+ collab: stub as unknown as CollabService,
+ authenticateRuntimeToken: async () => undefined
+ });
+ return calls;
+}
+
+describe("collab member routes", () => {
+ it("approves a join request from a signed-in account", async () => {
+ const calls = createApp();
+
+ const response = await app!.inject({ method: "POST", url: `/api/collab/projects/p-1/requests/${ACCOUNT_ID}/approve` });
+
+ expect(response.statusCode).toBe(200);
+ expect(calls).toEqual([`approve:${ACCOUNT_ID}`]);
+ });
+
+ it("rejects, promotes and removes a member by the same account id", async () => {
+ const calls = createApp();
+
+ await app!.inject({ method: "DELETE", url: `/api/collab/projects/p-1/requests/${ACCOUNT_ID}` });
+ await app!.inject({ method: "PATCH", url: `/api/collab/projects/p-1/members/${ACCOUNT_ID}`, payload: { role: "admin" } });
+ await app!.inject({ method: "DELETE", url: `/api/collab/projects/p-1/members/${ACCOUNT_ID}` });
+
+ expect(calls).toEqual([`reject:${ACCOUNT_ID}`, `role:${ACCOUNT_ID}`, `remove:${ACCOUNT_ID}`]);
+ });
+
+ it("keeps turning away ids that are not account ids", async () => {
+ createApp();
+
+ const response = await app!.inject({ method: "POST", url: "/api/collab/projects/p-1/requests/not-a-member/approve" });
+
+ expect(response.statusCode).toBe(400);
+ expect(response.json()).toMatchObject({ error: { code: "invalid_argument", message: "成员 ID 无效" } });
+ });
+
+ it("adds the current task with the project, directory and sentence the command sent", async () => {
+ const addCurrentSession = vi.fn(async () => ({ text: "已把当前任务「分享」加入协作项目「Memmy 开发」。" }));
+ app = Fastify();
+ registerCollabRoutes(app, {
+ collab: { addCurrentSession } as unknown as CollabService,
+ authenticateRuntimeToken: async () => undefined
+ });
+
+ const response = await app.inject({
+ method: "POST",
+ url: "/api/collab/sessions/add",
+ payload: { project: " Memmy 开发 ", cwd: "/repo", hint: "给分享接口加上限流" }
+ });
+
+ expect(response.statusCode).toBe(200);
+ expect(addCurrentSession).toHaveBeenCalledWith({ project: "Memmy 开发", cwd: "/repo", hint: "给分享接口加上限流" });
+ expect(response.json()).toEqual({ text: "已把当前任务「分享」加入协作项目「Memmy 开发」。" });
+
+ const rejected = await app.inject({
+ method: "POST",
+ url: "/api/collab/sessions/add",
+ payload: { cwd: "/repo", group: true }
+ });
+ expect(rejected.statusCode).toBe(400);
+ });
+});
diff --git a/App/backend/src/adapters/inbound/local-api/tests/projects-routes.test.ts b/App/backend/src/adapters/inbound/local-api/tests/projects-routes.test.ts
new file mode 100644
index 000000000..d98ad330e
--- /dev/null
+++ b/App/backend/src/adapters/inbound/local-api/tests/projects-routes.test.ts
@@ -0,0 +1,155 @@
+/** Local project routes: the managed folder a project created by name alone runs its tasks in. */
+import { mkdtemp, rm } from "node:fs/promises";
+import type { FastifyInstance } from "fastify";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import type { PermissionManager } from "../../../../permission/index.js";
+import { createProgressBus } from "../../../../services/progress-bus.js";
+import type { BackendServices } from "../../../../services/index.js";
+import {
+ createProjectDirectoryService,
+ type ProjectDirectoryService
+} from "../../../../services/project-directory-service.js";
+import {
+ createProjectInstructionsService,
+ type ProjectInstructionsService
+} from "../../../../services/project-instructions-service.js";
+import { createLocalApiServer } from "../server.js";
+
+let app: FastifyInstance | undefined;
+const roots: string[] = [];
+
+afterEach(async () => {
+ await app?.close();
+ app = undefined;
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+
+describe("project local api routes", () => {
+ it("prepares a managed working directory behind the runtime token", async () => {
+ const root = await mkdtemp(join(tmpdir(), "memmy-project-routes-"));
+ roots.push(root);
+ app = createServer(createProjectDirectoryService({ root }));
+
+ const response = await injectJson("POST", "/api/projects/working-directory", { name: "周报整理" });
+
+ expect(response.statusCode).toBe(200);
+ expect(response.json()).toEqual({ path: join(root, "周报整理") });
+ });
+
+ it("rejects the route without a runtime token", async () => {
+ app = createServer({ prepareManagedDirectory: async () => ({ path: "/tmp/unused" }) });
+
+ const response = await app.inject({
+ method: "POST",
+ url: "/api/projects/working-directory",
+ payload: { name: "周报整理" }
+ });
+
+ expect(response.statusCode).toBe(401);
+ });
+
+ it("rejects a project name that is only whitespace", async () => {
+ app = createServer({ prepareManagedDirectory: async () => ({ path: "/tmp/unused" }) });
+
+ const response = await injectJson("POST", "/api/projects/working-directory", { name: " " });
+
+ expect(response.statusCode).toBeGreaterThanOrEqual(400);
+ });
+
+ it("reads and saves a project's instructions, keyed by the project folder", async () => {
+ const root = await mkdtemp(join(tmpdir(), "memmy-project-instructions-routes-"));
+ roots.push(root);
+ const instructions = createProjectInstructionsService({ filePath: join(root, "project-instructions.json") });
+ app = createServer(undefined, instructions);
+ const directory = join(root, "memmy");
+
+ const empty = await injectJson("GET", `/api/projects/instructions?directory=${encodeURIComponent(directory)}`);
+ expect(empty.statusCode).toBe(200);
+ expect(empty.json()).toEqual({ text: "", origin: null, cloudProjectId: null, updatedAt: null });
+
+ const saved = await injectJson("PUT", "/api/projects/instructions", {
+ directory,
+ text: "本项目负责 Memmy 桌面端的研发。"
+ });
+ expect(saved.statusCode).toBe(200);
+ expect(saved.json()).toMatchObject({ text: "本项目负责 Memmy 桌面端的研发。", origin: "local" });
+
+ const read = await injectJson("GET", `/api/projects/instructions?directory=${encodeURIComponent(directory)}`);
+ expect(read.json()).toMatchObject({ text: "本项目负责 Memmy 桌面端的研发。" });
+ });
+
+ it("rejects instructions that are too long or a folder that is not absolute", async () => {
+ const root = await mkdtemp(join(tmpdir(), "memmy-project-instructions-limit-"));
+ roots.push(root);
+ app = createServer(undefined, createProjectInstructionsService({ filePath: join(root, "project-instructions.json") }));
+
+ const tooLong = await injectJson("PUT", "/api/projects/instructions", {
+ directory: join(root, "memmy"),
+ text: "字".repeat(10_001)
+ });
+ expect(tooLong.statusCode).toBe(400);
+
+ const relative = await injectJson("GET", "/api/projects/instructions?directory=memmy");
+ expect(relative.statusCode).toBeGreaterThanOrEqual(400);
+ });
+});
+
+async function injectJson(method: string, url: string, payload?: unknown) {
+ if (!app) throw new Error("Test server is not initialized");
+ return app.inject({
+ method,
+ url,
+ headers: { "x-memmy-local-token": "test-token" },
+ payload
+ });
+}
+
+function createServer(
+ projectDirectory?: ProjectDirectoryService,
+ projectInstructions?: ProjectInstructionsService
+): FastifyInstance {
+ const services = {
+ bootstrap: {
+ async getBootstrap() {
+ throw new Error("bootstrap not used");
+ }
+ },
+ progressBus: createProgressBus(),
+ ...(projectInstructions ? { projectInstructions } : {})
+ } as unknown as BackendServices;
+
+ return createLocalApiServer({
+ permissionManager: createPermissionManager(),
+ services,
+ ...(projectDirectory ? { projectDirectory } : {}),
+ heartbeatIntervalMs: 20
+ });
+}
+
+function createPermissionManager(): PermissionManager {
+ return {
+ async getRuntimeToken() {
+ return "test-token";
+ },
+ async verifyRuntimeToken(token) {
+ return token === "test-token";
+ },
+ async getScanPermission() {
+ return "scan_and_write_skill";
+ },
+ async setScanPermission() {
+ return undefined;
+ },
+ async canDetectAgentSources() {
+ return true;
+ },
+ async canScanAgentSource() {
+ return true;
+ },
+ async canWriteAgentSkill() {
+ return true;
+ }
+ } as unknown as PermissionManager;
+}
diff --git a/App/backend/src/adapters/outbound/agent-source/session-reference/local-session-rank.ts b/App/backend/src/adapters/outbound/agent-source/session-reference/local-session-rank.ts
new file mode 100644
index 000000000..94fb054e2
--- /dev/null
+++ b/App/backend/src/adapters/outbound/agent-source/session-reference/local-session-rank.ts
@@ -0,0 +1,63 @@
+/** Orders local sessions for the association picker. */
+import type { LocalSession } from "./local-session-reader.js";
+import { isSameOrInside } from "./session-group.js";
+
+/** What the person is doing when they ask for candidates. */
+export interface LocalSessionRankContext {
+ /** Keyword typed in the picker; empty when they just want recent sessions. */
+ query: string;
+ /** Directory whose sessions rank first, when the caller has one. */
+ cwd: string | null;
+}
+
+/**
+ * Returns the sessions to offer, best first. The caller keeps only the first few,
+ * so whatever ranks low here is effectively invisible.
+ */
+export function rankLocalSessions(sessions: readonly LocalSession[], context: LocalSessionRankContext): LocalSession[] {
+ // Most keywords matched first, then the asking conversation's directory, then the most recent.
+ // Matching any single keyword keeps a long pasted title from returning nothing at all.
+ return sessions
+ .map((session) => ({ session, score: matchScore(session, context.query) }))
+ .filter((entry) => entry.score > 0)
+ .sort((left, right) =>
+ right.score - left.score ||
+ Number(isSameWorkspace(right.session, context.cwd)) - Number(isSameWorkspace(left.session, context.cwd)) ||
+ lastActivityMs(right.session) - lastActivityMs(left.session))
+ .map((entry) => entry.session);
+}
+
+/**
+ * How many whitespace-separated keywords appear in the title, a question or the agent name.
+ * An empty query keeps everything, so the caller can list recents.
+ */
+export function matchScore(session: LocalSession, query: string): number {
+ const keywords = query.toLowerCase().split(/\s+/u).filter(Boolean);
+ if (!keywords.length) {
+ return 1;
+ }
+ const haystack = [session.title, session.agentName, ...session.turns.map((turn) => turn.question)]
+ .join("\n")
+ .toLowerCase();
+ return keywords.filter((keyword) => haystack.includes(keyword)).length;
+}
+
+/** True when at least one keyword matches. */
+export function matchesQuery(session: LocalSession, query: string): boolean {
+ return matchScore(session, query) > 0;
+}
+
+/** True when the session ran in the same directory as the asking conversation, or inside it. */
+export function isSameWorkspace(session: LocalSession, cwd: string | null): boolean {
+ if (!cwd || !session.workspacePath) {
+ return false;
+ }
+ // Windows 的路径是反斜杠,不能直接拼 `/` 比前缀。
+ return isSameOrInside(session.workspacePath, cwd);
+}
+
+/** Last activity as epoch milliseconds; unknown times sort last. */
+export function lastActivityMs(session: LocalSession): number {
+ const parsed = Date.parse(session.updatedAt);
+ return Number.isNaN(parsed) ? 0 : parsed;
+}
diff --git a/App/backend/src/adapters/outbound/agent-source/session-reference/local-session-reader.ts b/App/backend/src/adapters/outbound/agent-source/session-reference/local-session-reader.ts
new file mode 100644
index 000000000..9d3a24b97
--- /dev/null
+++ b/App/backend/src/adapters/outbound/agent-source/session-reference/local-session-reader.ts
@@ -0,0 +1,457 @@
+/**
+ * Local session reader. Lists this machine's agent sessions so a person can pick which ones to associate with an
+ * online project, and reads one session's turns so they can be uploaded to it. It runs in the desktop backend on
+ * the backend's own agent adapters, so online projects do not depend on the Memory service.
+ */
+import type { SourceRegistry } from "@memmy/agent-source-readers/adapters/source-registry";
+import type { ConversationMessage, SourceAdapter } from "@memmy/agent-source-readers/adapters/types";
+import { rankLocalSessions } from "./local-session-rank.js";
+import { readRecentSessionsFromMetadata } from "./session-metadata/index.js";
+import { createSessionGrouper, type LocalSessionGroup, type SessionGrouper } from "./session-group.js";
+import { finishSession, isInternalUserMessage, stripInjectedContext, type SessionBuilder } from "./session-shape.js";
+import { createStoreDigest, type StoreDigest } from "./store-digest.js";
+
+export type { LocalSessionGroup } from "./session-group.js";
+export { cleanQuestion, isHumanQuestion, isInternalUserMessage, stripInjectedContext } from "./session-shape.js";
+
+const DEFAULT_SESSIONS_PER_SOURCE = 30;
+/**
+ * 列表要的是任务数,而窗口按文件算:空记录、后台派生的记录不出现在列表里。凑不满时向前扩大窗口,
+ * 直到拿到要求数量的任务或到达这个上限。
+ */
+const RECENT_SCAN_FACTORS = [1, 2, 4] as const;
+/** A wider window used only when the recent list comes up short. */
+const WIDE_SESSIONS_PER_SOURCE = 200;
+/**
+ * 快照多久算旧。它现在只决定「多久拿摘要核对一次」——核对是几毫秒的 stat,不用再读盘,所以保持在 15 秒:
+ * 弹窗拿到的列表依旧不会超过这个时长,而每分钟的后台同步也不会因此重新扫一遍。
+ */
+const DEFAULT_SNAPSHOT_TTL_MS = 15_000;
+const DEFAULT_AVAILABLE_LIMIT = 50;
+const MAX_AVAILABLE_LIMIT = 500;
+/** Sessions one batch read may ask for; their turns all travel in one response. */
+export const MAX_READ_MANY = 50;
+
+/** One question and everything the agent did until the next question. */
+export interface LocalSessionTurn {
+ question: string;
+ reply: string;
+ steps: string[];
+ startedAt: string;
+}
+
+/** A local agent session reduced to what association and reading need. */
+export interface LocalSession {
+ sourceId: string;
+ agentName: string;
+ conversationId: string;
+ title: string;
+ lastQuestion: string;
+ workspacePath: string | null;
+ /** The agent's project or workspace, or the directory; null outside every unit. */
+ group: LocalSessionGroup | null;
+ updatedAt: string;
+ turns: LocalSessionTurn[];
+}
+
+/** A session as listed in the association picker, without its turns. */
+export interface LocalSessionCandidate {
+ sourceId: string;
+ agentName: string;
+ conversationId: string;
+ title: string;
+ lastQuestion: string;
+ workspacePath: string | null;
+ group: LocalSessionGroup | null;
+ updatedAt: string;
+ turnCount: number;
+}
+
+/** The candidate pool, and whether a newer scan is running behind it. */
+export interface LocalSessionListing {
+ sessions: LocalSessionCandidate[];
+ /** True when these came from the previous scan; asking again with `fresh` returns the newer one. */
+ refreshing: boolean;
+}
+
+/** Contract for the candidate pool the association picker chooses from. */
+export interface LocalSessionAvailableInput {
+ query?: string;
+ /** Sessions in this directory rank first. */
+ cwd?: string | null;
+ /** Only sessions of these agents, e.g. ["workbuddy"]; all agents when absent. */
+ sourceIds?: readonly string[];
+ limit?: number;
+ /** Waits for a current scan instead of answering from the previous one. */
+ fresh?: boolean;
+}
+
+/** Contract for local session reader. */
+export interface LocalSessionReader {
+ /** The agents' sessions, most relevant first; answers from the last scan while a newer one runs. */
+ available(input: LocalSessionAvailableInput): Promise;
+ /** Rereads one session so an upload carries its latest turns. */
+ read(input: { sourceId: string; conversationId: string }): Promise;
+ /**
+ * Rereads several sessions of one agent with one pass over its store. Reading them one by one costs a pass each,
+ * since a store is only read whole; `missing` lists the requested sessions it no longer has.
+ */
+ readMany(input: { sourceId: string; conversationIds: readonly string[] }): Promise<{ sessions: LocalSession[]; missing: string[] }>;
+}
+
+/** A read the caller can explain: an unknown agent or session, or a batch larger than one read allows. */
+export class LocalSessionReadError extends Error {
+ constructor(readonly code: "not_found" | "invalid_argument", message: string) {
+ super(message);
+ this.name = "LocalSessionReadError";
+ }
+}
+
+/** One agent store a scan should read, and the store it must read it from. */
+export interface LocalSessionScanRequest {
+ sourceId: string;
+ /** The store this source was seen at; a reader that only has the source id must refuse a store it does not own. */
+ dataPath: string;
+ /** How many of that source's most recent sessions to read. */
+ limit: number;
+}
+
+/**
+ * Reads the given stores somewhere else and answers with what it read, keyed by source id.
+ *
+ * A source it does not answer for is read on this thread as usual, so a reader that cannot keep up leaves the
+ * result unchanged and only gives back the responsiveness it was meant to save.
+ */
+export type LocalSessionScanOffload = (
+ requests: readonly LocalSessionScanRequest[]
+) => Promise>;
+
+export interface CreateLocalSessionReaderDeps {
+ registry: SourceRegistry;
+ /** When set, each scan reads this list instead of `registry.list()`, so added agents can be loaded from disk. */
+ adapters?: () => Promise;
+ sessionsPerSource?: number;
+ snapshotTtlMs?: number;
+ now?: () => number;
+ /** 判断某份存储有没有变的廉价摘要;默认浅层 stat 一遍,测试里可以换成假的。 */
+ storeDigest?: StoreDigest;
+ /**
+ * 把读盘交给别的线程。读一份存储是几秒的同步解析,留在调用方线程上会把同时到达的请求一起堵住;
+ * 没交出去、或者交出去没读成的源,照旧在本线程读。
+ */
+ offloadScan?: LocalSessionScanOffload;
+}
+
+/** Creates the local session reader. */
+export function createLocalSessionReader(deps: CreateLocalSessionReaderDeps): LocalSessionReader {
+ const sessionsPerSource = deps.sessionsPerSource ?? DEFAULT_SESSIONS_PER_SOURCE;
+ const snapshotTtlMs = deps.snapshotTtlMs ?? DEFAULT_SNAPSHOT_TTL_MS;
+ const now = deps.now ?? Date.now;
+ const storeDigest = deps.storeDigest ?? createStoreDigest();
+ /** 每份存储上次扫描时的摘要与结果:摘要没变就不用再读一遍。 */
+ const perSource = new Map();
+ /** 快照里装的是哪几个 Agent,权限变了会变。 */
+ let snapshotSources = "";
+ let snapshot: { loadedAt: number; sessions: LocalSession[] } | null = null;
+ let loading: Promise | null = null;
+
+ /** One live read of the agents' stores at a time, shared by every caller waiting on it. */
+ async function adapters(): Promise {
+ return deps.adapters ? deps.adapters() : deps.registry.list();
+ }
+
+ /**
+ * 扫描前先取各份存储的摘要:摘要对不上的才真去读盘。摘要比扫描早一步拿到,所以扫描期间刚写进来的内容
+ * 会让下次摘要对不上、多扫一遍,不会反过来漏掉。
+ */
+ async function currentDigests(list: readonly SourceAdapter[]): Promise