Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

feat(connectors progressive disclosure + meta-tools wiring + projects polish)

wyt3ba3e235cd5f
diff --git a/CLAUDE.md b/CLAUDE.md
index 9ef7e9be..c270dc8d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -10,15 +10,13 @@ Single-process Electron desktop app: main = Node backend, renderer = vanilla HTM
**Hard constraints**:
- main runs no HTTP / occupies no port / has no auth.
- - **Single documented exception**: `features/connectors/oauth.ts` binds an ephemeral 127.0.0.1 listener for the duration of one OAuth flow only (single `/callback` handler, auto-closes on success / timeout / quit). It's the standard desktop-OAuth pattern (Google Cloud SDK / gh / Notion CLI all do the same). It is **not** a general API surface — never extend this listener with other routes, never bind 0.0.0.0, never reuse it for non-OAuth purposes. Lifetime per flow is bounded by `FLOW_TIMEOUT_MS` (5 min); the call site auto-shuts the listener on completion. Any other feature that wants a localhost listener is forbidden.
- The renderer talks through the `contextBridge`-exposed `window.orkas.{invoke, stream}` allow-list API; **do not introduce** TS / JSX / webpack / vite.
- Preload **must be `.js`** (the preload loader does not run the tsx hook); path is `src/main/preload.js`.
- All LLM calls go through the in-process `core-agent` (`import('#core-agent')` dynamic load); no subprocesses. **Why:** avoid IPC serialization; locks / cancellation / event streams share memory.
- **Local CLI agents are the one explicit exception** — agents whose spec carries `runtime.kind === 'cli'` (claude code / codex / openclaw / opencode / hermes) are spawned as child processes by `features/local_agents/runner.ts`. **`features/local_agents/` is the sole `child_process.spawn` entry point for CLI dispatches**; `bus.ts` routes here, every other `features/*` module is forbidden from spawning these CLIs directly. **Why:** a single spawn entry guarantees uniform persistence (`<uid>/local/file_cache/local-agent-runs/<runId>/`), cancellation (AbortSignal → SIGTERM → 10s grace → SIGKILL), and 5-CLI fanout discipline — bypassing it leaks zombies and forks the run-history schema.
-- **MCP connector servers are a separate class with their own single spawn entry** — connector instances (see §6.5) spawn stdio MCP subprocesses via the `@modelcontextprotocol/sdk` `StdioClientTransport` inside `features/connectors/mcp-client.ts`, and **only there**. This is structurally analogous to the CLI-agent rule (one spawn entry per process class) but a separate code path: CLI agents are job runners producing one-shot answers; MCP servers are long-lived tool-providing daemons whose tools get folded into the in-process AgentRunner's `tools[]` array. Don't merge the two — they have different lifecycle, persistence, and cancellation rules.
- Storage is JSON / JSONL primarily; sqlite is used in exactly one place — the KB vector store. **Why:** user data must stay readable, portable, and friendly to cloud sync (single file = single sync unit).
- **skill / agent / contexts are three first-class citizens**; multi-agent collaboration follows the §5 group-chat architecture, with **no more "main agent calls subagent over RPC"**.
-- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp / adm-zip / cos-nodejs-sdk-v5 / @modelcontextprotocol/sdk`). **New dependencies require a discussion first.**
+- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp / adm-zip / cos-nodejs-sdk-v5`). **New dependencies require a discussion first.**
- Renderer-side third-party JS/CSS goes through static assets at `src/renderer/vendor/<name>/`; not via npm. **Why:** `require` is unavailable inside the contextBridge sandbox; routing through npm is actually a detour.
- **Cross-platform**: macOS + Windows are both primary (Linux is community-grade). New code prefers cross-platform implementations (Node stdlib); platform branches must be verified on real machines for each branch — getting one platform working is not enough.
- **Profile (region) routing**: `ORKAS_PROFILE` env selects which Orkas server region the PC talks to — `global` (default, `orkas.ai`) or `cn` (`orkas.work`). Mirrors Server `env/start/{dev_,}api_start.sh` (see Server CLAUDE.md §7). `run.sh` exports it from the first positional arg (`./run.sh cn`). Code that calls the Orkas API **must** route through `features/marketplace.ts::apiBase()` — never hard-code `orkas.ai` / `orkas.work`. Devs running against a local Server set `ORKAS_API_BASE_URL=http://127.0.0.1:8888/api` (overrides the profile lookup entirely). Telemetry / umami is intentionally NOT profile-gated (single-site analytics, see `renderer/modules/monitor.js` comment).
@@ -129,9 +127,9 @@ PC/data/
│ ├── skills/<sid>/ Custom skills (System A, scanned by SkillLoader)
│ ├── projects/<pid>/{project.json, bindings.json} Logical groups of conversations + per-project agent/skill scope (no aggregate index — list = directory scan)
│ ├── marketplace/installs.json Cloud-synced manifest of platform installs ({id, version, published_at, url} per agent + skill) — reconciled on startup
- │ └── config/{preferences,component-enabled}.json
+ │ └── config/{preferences,component-enabled,connectors}.json (connectors.json: plaintext envelope + per-instance vault-encrypted `secrets_enc`; seed = OAuth user_id — see §6.5)
└── local/ 🔒 Machine-private domain (never synced)
- ├── config/ User prefs (auth-profiles / permissions / reflection-state / web-search-cache / account = `(user_id, session_id)` + device_id + cached profile) — NEVER user-clearable
+ ├── config/ User prefs (auth-profiles / connector-oauth / permissions / reflection-state / web-search-cache / account = `(user_id, session_id)` + device_id + cached profile) — NEVER user-clearable
├── biz/ Server-sourced business data (marketplace.json — 24h TTL category registry); refresh-on-need but NOT user-clearable
├── marketplace/{agents,skills}/<id>/ Platform-installed content (per-machine copy reconciled from cloud installs.json)
├── cache/<bucket>/ User-clearable cache umbrella (marketplace/ today; file_cache / tool-results are slated to migrate here)
@@ -147,17 +145,20 @@ PC/data/
3. **Agent directory shape (per-agent asset aggregation)**: `<uid>/cloud/agents/<aid>/` contains `agent.json` (the sole UI display source — pure spec) + `meta/` (metacognition: COMPETENCE.md + LEARNING_STRATEGIES.md) + `skills/` (SkillStore self-evolved skills, visible only to this agent, not injected into the SkillLoader system-prompt block). Deleting an agent = `rm -rf <aid>/`, no cascade. See `docs/plans/agent-as-directory.md`. **Do not** revert to the old top-level `meta/` or `PC/skills/` (the SkillStore default cwd).
4. **`search/` indexes are purely derived**: never synced; mtime+size reconcile self-heals before each query; 1-second debounced flush + force flush on `before-quit`; rebuild automatically on schema change or corruption.
5. **The KB vector store is NOT cloud-synced (batch 2 decision)**: only `cloud/contexts/` source files cross devices; the `vector.db` + its `config.json` live at `<uid>/local/contexts/.kb/` (machine-private, NOT under cloud/). Each device's startup `kb_indexer.reconcile(uid)` rebuilds the index from the synced sources idempotently by sha1. One-shot migration `util/migrate-kb-to-local.ts` moves a pre-existing `<uid>/cloud/contexts/.kb/` directory into local/ on first launch (stamped under `.migrations`). **Why path mirrors cloud/contexts/ under local/contexts/**: keeps the mental model "KB lives under .../contexts/.kb/" intact across the cloud/local divide, so the cloud→local split is reflected in the path without renaming the `.kb` segment. **Why this changed from the earlier "vector.db IS synced" rule**: a single-doc edit kicks a hundreds-of-MB whole-DB re-upload — economics broke down once we wired the actual sync engine. Index rebuild is per-spec idempotent, so reuse it. **Journal mode is still DELETE, not WAL** (no benefit from switching; `kb_files` rows already use it).
-6. **Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**: COS bucket prefix = **OAuth `user_id`** (NOT the local 8-digit `uid`); per-machine path stays `<container>/data/<local_uid>/cloud/`, and `<oauth_user_id>/` is the cloud-side mirror. Why: same OAuth user has different local `uid` on each device — using local uid would scatter cloud data. The `features/sync/` engine is the **sole** writer of cloud→COS traffic and `<oauth_user_id>/cloud/*` keys; `features/sync/manifest.ts::commitManifest` (POST `/sync/manifest/commit`) is the **sole** writer of `<oauth_user_id>/manifest.json` (Server enforces atomicity via per-user lock + generation CAS + quota delta; see `Server/CLAUDE.md` §4). PC's STS scope is `<oauth_user_id>/*` for read, `<oauth_user_id>/cloud/*` for write — `manifest.json` is read-only for PC by design. **Five canonical sync triggers** funnel through `DirtyBus` / `engine.syncNow`: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), 5-minute periodic safety-net ticker (`engine.ts::PERIODIC_INTERVAL_MS`, bound to engine lifetime so the master switch gates it for free), before-quit. The 30s global floor between auto runs (`engine.ts::GLOBAL_FLOOR_MS`) applies to all except manual + before-quit (which bypass it intentionally; periodic respects it — a recent pass for any reason defers the next tick).
+6. **Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**: COS bucket prefix = **`private/<oauth_user_id>/`** (NOT the local 8-digit `uid`); per-machine path stays `<container>/data/<local_uid>/cloud/`, and `private/<oauth_user_id>/` is the cloud-side mirror. **Why the `private/` namespace**: leaves the rest of the bucket (e.g. `public/marketplace/skills/`) freely STS-scoped for non-user-private content; without it, widening any future public scope risks colliding with user data prefixes. **Why oauth_user_id (not local uid)**: same OAuth user has different local `uid` on each device — using local uid would scatter cloud data. The `features/sync/` engine is the **sole** writer of cloud→COS traffic and `private/<oauth_user_id>/cloud/*` keys; `features/sync/manifest.ts::commitManifest` (POST `/sync/manifest/commit`) is the **sole** writer of `private/<oauth_user_id>/manifest.json` (Server enforces atomicity via per-user lock + generation CAS + quota delta; see `Server/CLAUDE.md` §4). PC's STS scope is `private/<oauth_user_id>/*` for read, `private/<oauth_user_id>/cloud/*` for write — `manifest.json` is read-only for PC by design. **Five canonical sync triggers** funnel through `DirtyBus` / `engine.syncNow`: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), 5-minute periodic safety-net ticker (`engine.ts::PERIODIC_INTERVAL_MS`, bound to engine lifetime so the master switch gates it for free), before-quit. The 30s global floor between auto runs (`engine.ts::GLOBAL_FLOOR_MS`) applies to all except manual + before-quit (which bypass it intentionally; periodic respects it — a recent pass for any reason defers the next tick). **3-way pull classification** (`manifest.ts::classifyPullCandidates`, called from `_passBody` step 5): every path `diff()` puts into `need_pull` is routed by the (base, disk, remote) sha tuple — case A `base==disk` (local untouched, remote moved) → straight overwrite, **never push**; case B `base==remote` (local moved, remote untouched) → reclassify to push (legacy 3-way diff); case C three-way divergence → content-aware merge, then push the merge result back. **Why case A must not push**: a path whose on-disk bytes differ from base usually came from a prior merge's residue, NOT a fresh user edit — pushing it would publish the engine's own historical output as if it were a user change. We shipped this bug for a while and saw `pulled: 4 / pushed: 0` every pass for the same set of jsonl + mutable-json paths; the case A bucket is the load-bearing fix.
7. **Master switch defaults OFF** (user opt-in). `local/sync/state.json::enabled = false` until the settings card toggle turns it on. The engine's `init()` is a no-op while off, so login alone does not trigger any upload — there is exactly one moment data starts crossing the wire, and the user clicked a toggle to cause it.
+ - **`LOCAL_DATA_VERSION` data-version gate** (`features/sync/data_version.ts`): every PC build carries an integer schema-version constant; on each pass the engine compares it to `manifest.data_version` post-fetch and aborts with `pause_reason = 'version_outdated'` when `remote > LOCAL_DATA_VERSION` (Server mirrors the same gate on commit → `client_outdated` / 50404, which the engine handles as a sticky pause rather than a retry-able error). **When to bump + when NOT to + bumping procedure** are the MUST / MUST-NOT checklists in `data_version.ts`'s header comment — that file is the single source of truth for the call; don't restate the criteria elsewhere. **Why a third version field** when `manifest_v` and per-entry `schema_v` exist: they answer different questions — `manifest_v` is the manifest JSON's own structure, `schema_v` is per-file content format (with consumption logic still TODO in `merge/`), and `data_version` is the *global* application-data contract gate. Don't conflate them.
8. **`<uid>/local/cache/<bucket>/` is the user-clearable cache umbrella**. Anything dropped under `cache/` is fair game for the "clear cache" UI button (`features/cache_clearable.ts::clearAllClearable`). Distinct from `config/` (user prefs — never auto-cleared) and `biz/` (server-sourced reference data — refresh-on-need but not user-clearable). The marketplace content cache lives at `cache/marketplace/{agents,skills}/<id>/` with a per-entry `_cache.json` carrying `(server_id, version, published_at, fetched_at, last_used_at)`; entry-time sweep evicts entries idle > 7d AND LRU-trims when total > 100 MB (see `features/marketplace_cache.ts::sweepIfNeeded`, called once per `openMarketplace`). **Note**: `local/marketplace/{agents,skills}/<id>/` (the install target — constraint 2) is NOT under `cache/` and is NOT user-clearable; only the staging cache for browsing detail is. Future migration: `file_cache/` and `tool-results/` will move under `cache/` so a single "clear cache" hits all of them — DON'T yet rely on this; each owner module updates its path helper before the move.
-**uid lifecycle** (`features/users.ts`): on startup, `initActiveUser()` reads or creates `users.json` (8-digit numeric uids); `activateUser(uid)` is responsible for skeleton mkdir + injecting `process.env.CORE_AGENT_AUTH_DIR` + clearing caches. All user-scoped features get the uid via `getActiveUserId()` (throws if not activated). One active uid at a time for now.
+**uid lifecycle** (`features/users.ts`): on startup, `initActiveUser()` reads or creates `users.json` and calls `activateUser(uid)` (skeleton mkdir + injecting `process.env.CORE_AGENT_AUTH_DIR` + clearing caches + running migrations including `migrateLegacySessionIds`). All user-scoped features get the uid via `getActiveUserId()` (throws if not activated). One active uid at a time for now. **uid shape is unconstrained** — OrkasOpen first-boot generates 8-digit numeric via `genUserId()`; Hosted Orkas reconciles the local uid with the OAuth-issued user_id via `reconcileDevUid`, which today carries through whatever the server emits (UUID with dashes is real). Code that uses `<uid>/...` as a path segment is fine with any shape (single segment, no parsing). Code that USED to embed `<uid>-` into session_id has been removed (§5 — session_id is now `<kind>-<tail>`); never reintroduce that pattern.
-**User-account login (Google / Apple OAuth)** — all main-side code lives under `features/account/`, all renderer UI under `renderer/views/login/`; `index.ts` only hooks `account.registerProtocol()` + `account.bootstrap()`. Login state is a single sliding `SessionMgr` session — **no separate access/refresh token, no client-side refresh**: the provider handshake (`/account/oauth/{start,callback}` → one-time `exchange_code` → `/account/oauth/exchange`) returns `{user_id, session_id, user_info}`, and `user_id` + `session_id` (+ the cached `user_info` profile) are persisted **plaintext** to `<uid>/local/config/account.json` — same convention as `auth-profiles.json` and the rest of `<uid>/local/config/` (machine-private, never synced; protected by filesystem permissions, not in-file encryption). Authenticated requests carry `user_id` + `session_id` headers; the server renews the session on each one. At boot, a stored session → optimistic status `ready` from the disk cache immediately (no network wait), then one background authed call (`/account/points`) re-validates it — a 401 there flips to `needed` and re-shows the login gate; a transient failure keeps the optimistic `ready`. **This whole feature — `features/account/`, `ipc/account.ts`, `views/login/`, the `window.orkas.account` namespace + `account:changed` push, the `orkas://` scheme, the `account.*` i18n keys, the `#settings-account-group` block — is stripped from the OrkasOpen build** (open-source client has no account backend); the strip list is single-sourced in `OpenSource/SyncCode/strip-rules.json`.
+**User-account login (Google / Apple OAuth)** — all main-side code lives under `features/account/`, all renderer UI under `renderer/views/login/`; `index.ts` only hooks `account.registerProtocol()` + `account.bootstrap()`. Login state is a single sliding `SessionMgr` session — **no separate access/refresh token, no client-side refresh**: the provider handshake (`/account/oauth/{start,callback}` → one-time `exchange_code` → `/account/oauth/exchange`) returns `{user_id, session_id, user_info, subscription}` (subscription added by the membership-and-billing batch — see Server/docs/plans/membership-and-billing.md), and `user_id` + `session_id` (+ the cached `user_info` profile + `subscription` snapshot) are persisted **plaintext** to `<uid>/local/config/account.json` — same convention as `auth-profiles.json` and the rest of `<uid>/local/config/` (machine-private, never synced; protected by filesystem permissions, not in-file encryption). Authenticated requests carry `user_id` + `session_id` headers; the server renews the session on each one. At boot, a stored session → optimistic status `ready` from the disk cache immediately (no network wait), then one background authed call (`GET /account/me`, replacing the older `POST /account/points`) re-validates it AND refreshes the user_info + subscription snapshot in one round trip — a 401 there flips to `needed` and re-shows the login gate; a transient failure keeps the optimistic `ready`. **This whole feature — `features/account/`, `ipc/account.ts`, `views/login/`, the `window.orkas.account` namespace + `account:changed` push, the `orkas://` scheme, the `account.*` i18n keys, the `#settings-account-group` + `#settings-subscription-group` blocks — is stripped from the OrkasOpen build** (open-source client has no account backend); the strip list is single-sourced in `OpenSource/SyncCode/strip-rules.json`.
+
+**Membership-and-billing surface** (`features/account/subscription.ts` + the same `account.json` row carrying `subscription`): the snapshot rides on the existing `account:changed` push (`state.statusPayload.subscription`) — there is no second IPC channel for "tier-changed". The renderer's `views/login/account_settings.js::renderSubscriptionSettings()` reads from there + visibility-change re-fetch via `account.fetchMe()`. **Cloud sync and voice input are Pro-only** (Server-side gate via `require_entitlement("sync_enabled" | "voice_enabled")` in `Server/api/{sync,voice}.py`); the PC sync engine's master-switch in `local/sync/state.json::enabled` stays user-controlled, but writes will be 50403-rejected when `subscription.tier !== 'pro'` or status is non-active+non-grace — so the renderer's `sync_settings.js` should treat that as an expected failure mode (existing error UI surfaces it), not a bug. The renderer's only billing-action path is `account.openWebAccount()` → `/account/web_session/start` → `shell.openExternal` to the Web Account page; `BILLING_ACTIVE_PROVIDER=none` profiles render the Subscribe button as "Coming soon" (`account.subscription.billing_enabled` carries the answer; never gate on profile name). **Don't** mint a Stripe / Paddle URL inside the renderer — provider URL construction is server-side only (the entire reason the abstraction exists, see Server/CLAUDE.md §4).
**Voice-to-text in the chat composers** — the mic button next to the "+" attach button streams mic audio (renderer `getUserMedia` + AudioWorklet → 16 kHz PCM) over a WebSocket to the Orkas Server's `/voice/asr_ws` proxy (VolcEngine ASR). Renderer-side in `modules/voice-input.js`; the WS URL comes from the `voice.asrWsUrl` IPC handler, which resolves the same Server base as `features/account/server.ts::accountApiBase()` (`orkas.ai` prod; `ORKAS_VOICE_API_BASE` / `ORKAS_API_BASE_URL` override) and **requires login** — it reads `user_id`+`session_id` from the account session (in main) and appends them as a query pair (a browser `WebSocket` can't set an Authorization header); no session → the handler returns `{ok:false, error:'E_NOT_LOGGED_IN'}` and `voice-input.js` shows `chat.mic_login_required`. Mic access needs the renderer permission gate in `index.ts` (`setPermissionRequestHandler` grants `media`) plus `build.mac.extendInfo.NSMicrophoneUsageDescription` so packaged macOS shows the OS prompt. **Server-dependent → stripped from the OrkasOpen build** (offline client, no Server): `modules/voice-input.js`, the mic-button markup + `<script>` line in `index.html`, the `.chat-mic-btn` CSS, the `chat.mic_*` i18n keys, the `voice` namespace in `preload.js`, the `voice.asrWsUrl` handler in `ipc/index.ts` — single-sourced in `OpenSource/SyncCode/strip-rules.json`. (The permission gate + Info.plist key stay — they're feature-agnostic and a no-op without the mic button.)
-**iOS remote-control relay** — `features/relay/` (Server-dependent, **stripped from the OrkasOpen build** like `features/account/`). The companion `iOS/` app is a remote control: it can't run agents, it dispatches commands to this PC and watches progress. While the account is signed in (wired from `index.ts` after `account.bootstrap()` resolves to `ready`): `device.ts` registers this PC as a relay device + heartbeats (`device_id` reuses `account/token_store.ts::getDeviceId` — a stable per-machine UUID persisted in `account.json`); HTTP / WS calls attach `user_id` + `session_id` from `token_store.authHeaders()` (the unified SessionMgr credential — no separate access/refresh token layer); `commands.ts` long-polls `/relay/commands/poll` for commands the iOS app addressed to this device and delivers each as a user message via `group_chat.send` (→ `bus.enqueue`, the single dispatch primitive — **no parallel dispatch path**); `sync.ts` mirrors a `state.json::relay_enabled` conversation's `message` / `plan_changed` / `state_changed` bus events up to `/relay/conversations/sync` so the phone sees the same messages + plan rail. A relayed command's cid is the one the Server assigned (a fresh `rconv-…` for a new conversation, or the phone's existing cid); `chats.createConversation`'s `conversationId` option adopts it so both ends agree on the cid. **No server-side agent execution** — the Server `relay` module is a thin presence + queue + conversation-mirror layer (see Server CLAUDE.md); a server-side "云端" worker is a future decision, and the iOS device picker shows "云端" permanently greyed until then.
+**iOS remote-control relay** — `features/relay/` (Server-dependent, **stripped from the OrkasOpen build** like `features/account/`). The companion `iOS/` app is a remote control: it can't run agents, it dispatches commands to this PC and watches progress. While the account is signed in (wired from `index.ts` after `account.bootstrap()` resolves to `ready`): `device.ts` registers this PC as a relay device + heartbeats (`device_id` reuses `account/token_store.ts::getDeviceId` — a stable per-machine UUID persisted in `account.json`); HTTP / WS calls attach `user_id` + `session_id` from `token_store.authHeaders()` (the unified SessionMgr credential — no separate access/refresh token layer); `commands.ts` long-polls `/relay/commands/poll` for commands the iOS app addressed to this device and delivers each as a user message via `group_chat.send` (→ `bus.enqueue`, the single dispatch primitive — **no parallel dispatch path**); **the poll is true long-poll** — Server BRPOPs up to ~25 s, so PC chains the next call on response (no `setInterval` cadence) and bounds each call with an `AbortController` (`PER_CALL_TIMEOUT_MS = 35 s` in `commands.ts`). **Don't reintroduce a fixed inter-poll delay** — Server controls cadence via BRPOP; a client-side delay just adds latency between commands; `sync.ts` mirrors a `state.json::relay_enabled` conversation's `message` / `plan_changed` / `state_changed` bus events up to `/relay/conversations/sync` so the phone sees the same messages + plan rail. A relayed command's cid is the one the Server assigned (a fresh `rconv-…` for a new conversation, or the phone's existing cid); `chats.createConversation`'s `conversationId` option adopts it so both ends agree on the cid. **No server-side agent execution** — the Server `relay` module is a thin presence + queue + conversation-mirror layer (see Server CLAUDE.md); a server-side "云端" worker is a future decision, and the iOS device picker shows "云端" permanently greyed until then.
---
@@ -165,24 +166,24 @@ PC/data/
| Conversation type | UI message list | session_id |
|---|---|---|
-| Main conversation (group chat) — commander | `<uid>/cloud/chats/<cid>.jsonl` | `<uid>-gconv-<cid>` |
-| Main conversation (group chat) — agent worker | `<uid>/cloud/chats/<cid>/visibility/<aid>.jsonl` | `<uid>-gmember-<cid>-<aid>` |
-| Skill editing | `<uid>/cloud/chats/skill/<sid>/chat.jsonl` | `<uid>-skill-<sid>` |
-| Agent editing | `<uid>/cloud/chats/agent/<aid>/chat.jsonl` | `<uid>-agent-<aid>` |
-| KB image understanding | (no UI) | `<uid>-extract-img-<hex>` |
-| CLI agent dispatch | (no jsonl — per-run files only) | `<uid>-cli-<cli>-<runId>` |
+| Main conversation (group chat) — commander | `<uid>/cloud/chats/<cid>.jsonl` | `gconv-<cid>` |
+| Main conversation (group chat) — agent worker | `<uid>/cloud/chats/<cid>/visibility/<aid>.jsonl` | `gmember-<cid>-<aid>` |
+| Skill editing | `<uid>/cloud/chats/skill/<sid>/chat.jsonl` | `skill-<sid>` |
+| Agent editing | `<uid>/cloud/chats/agent/<aid>/chat.jsonl` | `agent-<aid>` |
+| KB image understanding | (no UI) | `extract-img-<hex>` |
+| CLI agent dispatch (devtools archive only) | (no jsonl — archive only) | `cli-<cli>-<runId>` |
-session jsonl files land at `<uid>/cloud/sessions/<session_id>.jsonl` — they are **two independent files** from the UI message list.
+session jsonl files land at `<uid>/{cloud,local}/sessions/<session_id>.jsonl` (cloud for resumable kinds gconv/gmember/skill/agent; local for ephemeral extract-img/reflect/memory-extract/anon — see `model/core-agent/session-store.ts::EPHEMERAL_KINDS`) — they are **two independent files** from the UI message list.
-**Project membership** is an index-level field on the conv record (`Conversation.project_id`), **not** part of any path or session_id. cid stays globally unique; `<cid>.jsonl` / `groupChatDir` / `chat_attachments/<cid>/` / `session_id = <uid>-gconv-<cid>` paths are independent of project membership. Project membership has effect in two places, both resolved once at the top of `runTurn` and threaded through `ChatOptions`: (1) **workspace** — `getWorkspacePath(uid, projectId?)` (sync) picks the project-scoped selection from `<uid>/local/workspace.json::projects[pid]` when set, falling through to `default.selectedPath` then `DEFAULT_USER_WORKSPACE`; (2) **agent/skill scope** — `projects.resolveProjectScope(uid, projectId)` returns the project's `bindings.json` (`{agents, skills}`), which restricts the commander's agents-index render and the System A skill render to those ids only. Orphan conversations (no `project_id`) keep legacy global visibility. group_chat threads `projectId` + `projectAllowedSkillIds` through `ChatOptions` → `LocalToolsOpts` / `FileToolsOpts` / `ImageGenToolOpts` / `getSystemPromptBlock`. **Do not** re-read the conv index or bindings per tool call — the resolved values travel with the turn.
+**Project membership** is an index-level field on the conv record (`Conversation.project_id`), **not** part of any path or session_id. cid stays globally unique; `<cid>.jsonl` / `groupChatDir` / `chat_attachments/<cid>/` / `session_id = gconv-<cid>` paths are independent of project membership. Project membership has effect in two places, both resolved once at the top of `runTurn` and threaded through `ChatOptions`: (1) **workspace** — `getWorkspacePath(uid, projectId?)` (sync) picks the project-scoped selection from `<uid>/local/workspace.json::projects[pid]` when set, falling through to `default.selectedPath` then `DEFAULT_USER_WORKSPACE`; (2) **agent/skill scope** — `projects.resolveProjectScope(uid, projectId)` returns the project's `bindings.json` (`{agents, skills}`), which restricts the commander's agents-index render and the System A skill render to those ids only. Orphan conversations (no `project_id`) keep legacy global visibility. group_chat threads `projectId` + `projectAllowedSkillIds` through `ChatOptions` → `LocalToolsOpts` / `FileToolsOpts` / `ImageGenToolOpts` / `getSystemPromptBlock`. **Do not** re-read the conv index or bindings per tool call — the resolved values travel with the turn.
-**Security invariant**: `session_id` must be `<uid>-<kind>-<tail>`, with the uid in the first segment, and `<kind>` ∈ `gconv | gmember | skill | agent | extract-img | reflect | memory-extract | anon | cli` (`sub` / `organizer` / `conv` are legacy kinds; new code does not generate them, but `migrate-session-ids` preserves these older files). `session-store.ts::sessionFileFor()` enforces this with hard assertions to prevent cross-uid leakage. **Do not** encode brand names (`orkas-` / `aiteam-` / any app name) into session_id — we hit the renaming-breaks-history pitfall once, the startup `migrateLegacySessionIds(uid)` strips legacy prefixes once, and new code never adds them again. Adding a new kind requires extending this table. The `cli` kind has no `sessions/*.jsonl` (CLI dispatches do not run through core-agent); the id exists purely to give per-run records a stable, kind-tagged identifier.
+**Security invariant**: `session_id` is `<kind>-<tail>` — the kind keyword anchors the FIRST segment, and `<kind>` ∈ `gconv | gmember | skill | agent | extract-img | reflect | memory-extract | anon | cli` (`sub` / `organizer` / `conv` are legacy kinds; new code does not generate them, but `migrate-session-ids` preserves these older files). **User scoping is provided by the path root** (`<activeUid>/{cloud,local}/sessions/<sid>.jsonl` resolved via `getActiveUserId()` in `model/core-agent/session-store.ts::sessionFileFor`); the session_id intentionally does NOT carry uid — a previous design embedded uid as the first segment, but it was redundant with the path root (sessionFileFor was self-checking the prefix it had just been handed) AND it forced uid to be dash-free, which broke when OAuth UUIDs entered the system. `resolveSessionPath` enforces the kind-anchor with a hard assertion (rejects ids that don't start with a known kind, blocks accidental hand-built ids). **Do not** prefix brand names (`orkas-` / `aiteam-` / any app name) or uid into session_id — startup `migrateLegacySessionIds(uid)` rewrites every legacy shape (`<brand>-<uid>-<kind>-<tail>` / `<uid>-<kind>-<tail>`) to `<kind>-<tail>` once. Adding a new kind requires extending this table + `session-store.ts::KNOWN_KINDS_RE` + (if it should expose connectors) `runner.ts::connectorExposureFromSessionId`. The `cli` kind is **devtools-only**: CLI dispatches don't write to `sessions/*.jsonl` (no core-agent session); the id exists purely to give the LLM-debug archive a stable, kind-tagged identifier.
**Skill injection policy**: edit conversations + group-chat commander = no filtering (inject all); group-chat agent worker = filter by `agent.skill_list` three-state (see §6).
**Prompt-cache convention**: continuous sessions (`gconv-* / gmember-* / skill-* / agent-*`) default to `cacheRetention: 'short'`; one-shot calls (memory / reflection / KB image) do not pass it. pi-ai already abstracts provider differences (the features layer does no branching). `'long'` is off by default (Anthropic's 1h has a 2× write surcharge).
-**Adding a new conversation type**: UI path must contain a `user_id` segment + session_id uses the `<uid>-<kind>-<tail>` three-segment format (uid first segment, **no brand prefix**) + conversation-level rules go through `ChatOptions.systemPrompt` (rebuilt every time, **don't splice them into the first user message as a prefix**) + update this table.
+**Adding a new conversation type**: UI path must contain a `user_id` segment + session_id uses the `<kind>-<tail>` format (kind first segment, **no uid / brand prefix** — see Security invariant above) + conversation-level rules go through `ChatOptions.systemPrompt` (rebuilt every time, **don't splice them into the first user message as a prefix**) + update this table.
### Group-chat architecture (`features/group_chat/`)
@@ -269,36 +270,46 @@ Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplac
## 6.5 Connectors (MCP-based)
-Third-party tool integrations attach via MCP servers (`@modelcontextprotocol/sdk`); Orkas is purely an MCP **client**, and **every installable connector uses OAuth 2.0** — no API-key / PAT entry point in the user-facing surface. We don't host first-party MCP servers; the chosen community MCP server is spawned locally (stdio) or reached remotely (streamable-http) with the user's OAuth `access_token` injected per the catalog entry's transport template at every spawn.
+Third-party integrations attach via MCP servers (`@modelcontextprotocol/sdk`); Orkas is purely an MCP **client**. **Every installable connector uses OAuth 2.0** — no API-key / PAT entry in the user-facing surface; `manager.connectViaOAuth(catalogId)` is the only install path. We don't host first-party MCP servers — community servers are spawned locally (stdio) or reached remotely (streamable-http) with the OAuth access_token injected per the catalog's `transport_template` at every spawn.
-**Curated catalog**: every installable connector is a row in `features/connectors/catalog.ts::CONNECTOR_CATALOG`. Each entry declares `oauth` (the per-provider OAuth 2.0 endpoints + default scopes + PKCE / secret flags) and `transport_template` (the MCP server we spawn, with either `oauth_env_key` or `env_synthesizer` describing how the access_token reaches the server). UI renders one card per catalog row. **Adding a new connector** = append to the catalog (set `transport_template: null` + `unavailable_reason: 'oauth_pending'` when the MCP server target isn't selected yet; otherwise wire `oauth_env_key` / `env_synthesizer`). `manager.connectViaOAuth` is the only public install path — there is no free-form / API-key entry.
+**OAuth refresh**: lazy at boot / on next reconnect / on `刷新工具` — **no background timer**. **Per-instance dedupe lock** in `manager.ts::_refreshGrantIfStale`: refresh_tokens rotate on every exchange (GitHub `ghr_*`, Notion DCR, etc.); two concurrent `_resolveTransport` callers POSTing the same stale refresh_token would both succeed for one and fail with `bad_refresh_token` for the other → connector permanently broken. Lock coalesces concurrent callers onto a single in-flight Promise + re-reads instance from registry inside the lock so a just-released caller's persisted grant is picked up.
-**OAuth flow**: PKCE + ephemeral 127.0.0.1 callback listener (the §1 single-spawn exception). `features/connectors/oauth.ts::startOAuth` runs the full flow, returns an `OAuthGrant`. `refreshIfStale` runs lazily at boot / `connectors.refresh` / on the next reconnect — no background timer. Mid-call expiry surfaces as a tool error; the user re-clicks "刷新工具" and the manager re-resolves the transport with a freshly-refreshed token.
+**Status writes never use `registry.upsert(snapshot)`** — only `registry.update(patch)`. Spreading an entry-time `inst` snapshot would clobber the rotated `oauth_grant` written by a concurrent refresh (same race as above, the second leg of the same bug). `connectViaOAuth`'s initial `upsert(draft)` is the only exception (no concurrent writers — fresh row).
-**Provider client credentials**: `client_id` / `client_secret` come from `features/connectors/oauth-config.ts`, two sources in priority order:
+**Provider client credentials** come from `features/connectors/oauth-config.ts` in priority order:
1. Env vars `ORKAS_OAUTH_<PROVIDER>_CLIENT_ID` / `..._SECRET` — baked into Hosted Orkas builds.
-2. `<uid>/local/config/connector-oauth.json` (BYO mode for OrkasOpen / power users who registered their own apps).
+2. `<uid>/local/config/connector-oauth.json` — BYO for OrkasOpen / power users.
-A catalog entry without resolvable credentials renders disabled in the gallery (`需先配置 OAuth`). The OrkasOpen build inherits the catalog and the BYO flow as-is; nothing in `features/connectors/` is stripped — connectors are still 100% client-side.
+**Storage**: `<uid>/cloud/config/connectors.json` — **plaintext JSON envelope**; each instance's `oauth_grant` + `dcr_client` + `transport` collapse into a single per-instance `secrets_enc` field encrypted via `util/crypto-vault.ts` (PBKDF2 → AES-256-GCM). **Why field-level, not whole-file**: metadata (`display_name` / `status` / `tools_cache` / timestamps) needs to be Server-readable so iOS / the components-view path can list connectors without holding the vault key; the token-bearing blob stays sealed. **`transport` is in the encrypted blob** even though it isn't a "secret" by name — `applyTemplate` bakes the resolved `access_token` into `transport.env[oauth_env_key]` (stdio) / `transport.headers.Authorization` (streamable-http), so leaving it plaintext defeats the encryption. Runtime cost is zero: `manager.ts::_resolveTransport` re-runs `applyTemplate` from catalog template + fresh `oauth_grant` on every connect, the persisted transport is purely vestigial. The read path also accepts the legacy whole-file vault format produced by `LOCAL_DATA_VERSION ≤ 1` builds — next write upgrades the file in place; `LOCAL_DATA_VERSION` is bumped to 2 because an older PC reading the new shape would silently drop every instance's grant. **Vault seed = OAuth user_id when logged in, local uid as fallback** (OrkasOpen / pre-login). Same Orkas account on N devices → same OAuth user_id → all devices decrypt the cloud-synced file. Logout doesn't destroy the file; re-login to the same account restores access. **Cloud-synced as of 2026-05-15** (was local-only — the migration `util/migrate-connectors-to-cloud.ts` runs once post-login). **Obfuscation-grade**, not keychain-strength — accepted for portability inside the data directory (no OS-keystore dependency). `auth-profiles.json` and `connector-oauth.json` keep local-uid seeds + whole-file vault and stay machine-private (LLM provider keys and BYO OAuth client config don't follow the user across devices).
-**Storage**: single file `<uid>/local/config/connectors.json` (path helper: `paths.ts::userConnectorsConfigFile`). Encrypted via `util/crypto-vault.ts` (PBKDF2 → AES-256-GCM, key derived from the active uid + a compile-time app salt). `connector-oauth.json` uses the same vault. **The encryption is obfuscation-grade**, not keychain-strength — see `util/crypto-vault.ts` header. The product owner accepted that trade-off explicitly to keep everything portable inside the data directory (no OS-keystore dependency). The same vault wraps `auth-profiles.json` (LLM provider credentials) since those are credentials of equal sensitivity.
+**Tool injection (umbrella pattern)** — `model/core-agent/connector-meta-tools.ts`:
+- System prompt carries a `## Connectors` block enumerating visible connectors (one line per: id + display_name + catalog description + optional account_label).
+- `tools[]` carries TWO meta-tools: `list_connector_tools(connector_id)` + `call_connector_tool(connector_id, tool_name, args)`.
+- **Per-connector MCP actions are NEVER injected into `tools[]`** — the model reads the catalog from the block and discovers per-action schemas through `list_connector_tools`. Reintroducing flat injection re-exposes the 20–50 tool-selection-accuracy cliff (Anthropic 30–50 / Cursor ~40 / Cline ~20 / Copilot 128 hard cap with degradation well below) AND invalidates the prompt-cache prefix (`tools → system → messages`) on every connect/disconnect.
+- Block carries **no protocol-teaching paragraph** — per-role chat prompts teach their own usage (commander/agent-worker invoke; agent-edit references action names in `<workflow>`).
+- All three (block + both tools) are omitted entirely when zero connectors are visible to the actor; `tools[]` shrinks accordingly and the model has no broken affordance.
+- Visibility is single-sourced through `tools-adapter.ts::resolveVisibleConnectors`.
+- Tool name shape `<instance_id>__<mcp_tool_name>` is retained for internal routing + dev archive but no longer surfaces to the model.
-**Lifecycle**: `features/connectors/manager.ts` is the process singleton. `bootstrap(uid)` reads the registry and reconnects everything in parallel at boot; `before-quit` calls `shutdownAll()` so stdio subprocesses (the MCP servers) exit instead of becoming zombies. Status flips on each turn (`connected | connecting | disconnected | error`) are persisted but treated as best-effort — the live `Map<id, McpConnection>` is the truth at runtime.
+**Visibility filters** (composed left-to-right by `resolveVisibleConnectors`):
+1. **Live-state**: only `status.kind === 'connected'` instances surface. Connecting / disconnected / error are silently hidden — `callTool` would throw anyway, and a "disconnected, ask user to refresh" hint is noise mid-task. **Don't reintroduce a status suffix** in the block.
+2. **Per-user enable toggle** (`<uid>/cloud/config/component-enabled.json::connectors`, shared with agents/skills, only `false` persisted): cloud-synced soft-disable. Disabled-but-connected instances keep their OAuth grant + live MCP session, but are invisible to the LLM (no block line; `list_connector_tools(<id>)` returns `E_CONNECTOR_NOT_VISIBLE`). **Why two switches** ("停用" vs "断开"): "断开" wipes the grant + requires re-OAuth to recover; "停用" is one-click reversible — the right UX for "mute for now, might re-enable in 5 min".
+3. **Per-agent whitelist** `agent.enabled_connectors`: **diverges from `agent.skill_list`'s three-state** — `undefined` and `[]` BOTH collapse to "no connectors"; only non-empty `string[]` grants access. Connectors carry external side effects, so a brand-new agent must opt in explicitly. UI-only field — agent-edit LLM never authors it (no `<agent>` sub-tag).
-**Tool injection (umbrella meta-tools + system-prompt block)**: connectors are exposed through (1) a `## Connectors` markdown block injected into the system prompt enumerating each visible connector (`- **<id>** — <display_name>: <description> [(account: <label>)] [— <status>]`; status suffix appears only when the instance is not `connected`; account suffix only when the OAuth grant carries `account_label`; description pulled from `catalog.ts::CONNECTOR_CATALOG[*].description_{zh,en}` in the user's UI language), plus (2) two meta-tools — `list_connector_tools(connector_id)` (returns the JSON schemas for one connector's actions) and `call_connector_tool(connector_id, tool_name, args)` (routes to `manager.callTool`). Both come from `model/core-agent/connector-meta-tools.ts` (`getConnectorPromptBlock` + `createConnectorMetaTools`). The block carries no protocol-teaching paragraph — each per-role chat prompt teaches its own usage (commander / agent-worker → invoke; agent-edit → reference by id in workflow). Per-connector MCP actions are NEVER injected into `tools[]` — the model reads the catalog from the system-prompt block (no discovery round-trip), gets per-action schemas from `list_connector_tools`, and invokes through `call_connector_tool`. The visibility resolver `features/connectors/tools-adapter.ts::resolveVisibleConnectors` is shared by both meta-tools and the prompt block so the actor matrix (commander vs. agent worker / `enabled_connectors` whitelist / instance-level `enabled_subtools` filter) is single-sourced. **The block + both tools are omitted entirely when zero connectors are visible to the actor** — `tools[]` shrinks by two slots, the system prompt stays smaller, and the model has no broken affordance to call.
+**Session-kind gate** (`runner.ts::connectorExposureFromSessionId`, tri-state):
+- `gconv` (commander) + `gmember` (agent worker) → **block + both tools** (full exposure for actual user tasks).
+- `agent` (agent-edit) → **block + `list_connector_tools` only**. Editor LLM needs to learn action names + schemas so the authored `<workflow>` can write specific steps; `call_connector_tool` is withheld so authoring sessions never fire external side effects. The block in this mode **bypasses `agent.enabled_connectors`** (passes `undefined` agentId) — chicken-and-egg, the editor must see every installed connector to recommend referencing one the user can then toggle on.
+- `skill` (skill-edit) / KB-image / CLI dispatch / reflect / memory-extract / anon → **none**. Adding a kind that needs connectors: extend this gate explicitly + add an entry to §5's session-id table.
-**Session-kind gate (tri-state)** (`runner.ts::_connectorExposure`):
- - `gconv` (commander) + `gmember` (agent worker) → **block + tools** (full exposure: read catalog AND invoke).
- - `agent` (agent-edit chat) → **block only** (the editor LLM authoring the agent's `<workflow>` needs to know which connectors exist so it can write "use the `notion` connector to …" or similar; the meta-tools themselves are NOT injected — an authoring session must not produce external side effects). The block in this mode bypasses `agent.enabled_connectors` (passes `undefined` agentId to `getConnectorPromptBlock`) — the editor LLM must see EVERY installed connector even if the agent's current allowed-list hasn't been opened to it yet, otherwise it can't recommend referencing one (chicken-and-egg: the user toggles `enabled_connectors` separately in the agent-edit UI's "Allowed connectors" section, not via the LLM).
- - `skill` (skill-edit) / KB-image / CLI dispatch / reflect / memory-extract / anon → **none** (no block, no tools — these aren't user-task surfaces and shouldn't fire external side effects). Adding a new conversation kind that needs connectors? Extend `_connectorExposure` explicitly + add an entry to §5's session-id table.
+**Lifecycle**: `manager.ts` is the process singleton. The live `Map<id, McpConnection>` is the runtime truth; persisted `status` is best-effort and lags. `before-quit` calls `shutdownAll()` so stdio subprocesses don't leak.
-**Why the umbrella architecture**: keeps `tools[]` size constant regardless of connector count, avoiding the 20–50 tool-selection-accuracy cliff every major LLM hit in 2025–2026 (Anthropic 30–50 / Cursor ~40 / Cline ~20 / Copilot 128 hard cap with degradation well below); preserves the Anthropic prompt-cache prefix (`tools → system → messages`) across connect/disconnect events (the block is part of the appended system prompt, stable per session); provider-agnostic under the pi-ai abstraction (no dependency on Anthropic's private Tool Search Tool). Static `TOOL_CATALOG` (§3) enumerates the two meta-tools but **not** the dynamic per-connector actions (they vary per-user). Tool name shape `<instance_id>__<mcp_tool_name>` is retained for internal routing + the dev archive but no longer surfaces to the model.
+**Spawn discipline** (per §1): `mcp-client.ts` is the sole entry for MCP stdio `child_process.spawn`; `oauth.ts` is the sole localhost-listener exception. Everything else routes through `manager.{callTool, connectViaOAuth}`.
-**Per-agent scope**: `agent.enabled_connectors` is a whitelist of instance ids. **Semantics intentionally diverge from `agent.skill_list`'s three-state**: missing/`undefined` and `[]` BOTH collapse to "no connectors"; only a non-empty `string[]` grants access. **Why:** connectors carry external side effects (sending emails, mutating remote docs) — a brand-new agent must opt in explicitly, while skills are passive instructions where "no filter" is a reasonable default. The Commander (agentId === undefined at the runner level) sees every connected instance — it's the routing layer and needs full visibility. The field is authored exclusively in the agent edit UI's "Allowed connectors" section, not by the agent-edit LLM (the `<agent>` container has no sub-tag for it). Under the umbrella architecture, the whitelist controls what appears in the `## Connectors` system-prompt block at runtime (gmember sessions); when the resulting visible set is empty, the block AND both meta-tools are omitted from the runner output. **Agent-edit sessions deliberately ignore the whitelist** (see the tri-state gate above) so the editor LLM can recommend a connector the agent hasn't been opened to yet.
+**Stdio adapter for vendor-blocked MCP** (`PC/bin/<svc>-mcp-server.cjs`): when a vendor's hosted MCP requires preview/allowlist enrollment (e.g. `gmailmcp.googleapis.com`), wrap the underlying public REST API in a local CJS stdio server. Catalog template uses `${ORKAS_NODE}` / `${ORKAS_PC_DIR}` placeholders that `apply-template.ts` resolves to Electron-as-Node + (asar.unpacked-aware) PC root. **CJS, not TS** — the child runs raw Node, no tsx; deps limited to `@modelcontextprotocol/sdk` + stdlib. **Token refresh** is handled by `manager.callTool` respawning the child when `expires_at` is within `REFRESH_BUFFER_MS`; the child has no refresh-token plumbing of its own.
-**Spawn discipline**: §1 calls out `features/connectors/mcp-client.ts` as the sole spawn entry for MCP stdio subprocesses, and `features/connectors/oauth.ts` as the sole localhost-listener exception. Other modules use `manager.callTool` / `manager.connectViaOAuth` — no direct `child_process` / transport / HTTP listener outside these two files.
+**Catalog bundles** (`CatalogEntry.bundle_member_ids`): a catalog entry can declare itself a **UI-only grouping** that fans out on connect. The bundle entry has `transport_template: null` and never becomes a ConnectorInstance — `manager.connectViaOAuth` runs OAuth once for the bundle (Server returns a grant with the union of all members' scopes, e.g. `_SCOPES_BY_CATALOG_ID['google-workspace']`) and provisions one instance per member with a deep-cloned grant. **Model view is unchanged**: each member stays a distinct connector with its own tools. Renderer hides member entries, shows the bundle card; disconnect / enable-toggle fan out across all members. Used today for `google-workspace`.
-**OrkasOpen**: connectors have no Server dependency, so the entire `features/connectors/` tree + the renderer's `panel-connectors` + locale keys + `enabled_connectors` field stay in the OrkasOpen build. (Marketplace-style recommended-connectors UI, if added later, can be conditionally hidden the same way `marketplace_dev` is — see §9 OrkasOpen contract.)
+**OrkasOpen**: nothing in `features/connectors/` is stripped — connectors are 100% client-side. (A future marketplace-style recommended-connectors UI would gate the same way `marketplace_dev` does — see §9 OrkasOpen contract.)
---
@@ -344,7 +355,6 @@ Strings live in `src/{renderer,main}/locales/{zh,en}.json`; lookup goes through
- All user-visible strings (button / title / status / placeholder / tooltip / empty state / toast / dialog) **must go through i18n** with both zh and en keys.
- Static HTML uses `data-i18n*` (`applyDomI18n()` auto-fills); **JS-injected text must subscribe to `i18n-change` and re-render** — common misses: sidebar lists / settings dynamic rows / status-toggle buttons.
- Decide the i18n key first, then write the code; **no hard-coded Chinese with "I'll backfill later"**.
-- **No fallback strings on `t()` calls** — never write `t('foo.bar') || 'Fallback…'`. Locale tables are the single source of truth; a missing key is a bug, not a "graceful degradation" condition. **Why:** fallback strings drift away from the locale tables (the tables stop being authoritative), they leak source text into a language the file is supposed to be neutral toward (Chinese fallbacks in source violate the project's English-only-source rule), and they hide missing-key bugs that would otherwise surface immediately. **The rule:** add the key to both `zh.json` and `en.json` before the code can ship; if a key is missing the raw key string surfaces in UI (per `t()`'s built-in raw-key fallback) and the dev fixes it. Same rule applies to `t()` arguments that are interpolated into HTML — write the key, not a `||` chain.
- **Not i18n-ed**: LLM prompts (`prompts/*.md` — the source language IS the prompt), logs, telemetry event names, user content.
---
@@ -401,7 +411,8 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
**Layering / paths**:
- Write business in `ipc/` (skipping a layer); call core-agent directly / spawn processes from `features/`.
-- Storage paths missing the `<uid>` segment; session_id where the second segment isn't the uid.
+- Storage paths missing the `<uid>` segment.
+- Embed `<uid>` into session_id (e.g. `<uid>-gconv-<cid>` or `<kind>-<uid>-<tail>` or any other shape that puts uid into the filename). session_id is `<kind>-<tail>` (per §5) — user scoping comes from the path root (`<activeUid>/{cloud,local}/sessions/<sid>.jsonl`), not from the filename. Embedding uid was a previous design that turned out redundant with path scoping AND forced uid to be dash-free, breaking every UUID-shaped uid (OAuth user_id). The 17 producer + matcher sites that used to do this have been swept; new code that does it gets caught by `session-store::resolveSessionPath`'s kind-anchor assertion (which throws on any id that doesn't start with a known kind keyword).
- Cache uid paths as a module-level `const` in a feature module (must call `getActiveUserId()` each time).
- Add `window.orkas.*` in the renderer without adding a handler in `ipc/index.ts`.
- Bypass `util/locks.ts` / `util/path-sandbox.isPathAllowed` / `features/file_indexer.ts`.
@@ -412,9 +423,9 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
- Apply the project agent/skill scope as a 5th `component_enabled` filter site. Project scope is an OUTER intersection plumbed through the existing render entry points (`buildAgentsIndexBlock` `allowedIds` / `getSystemPromptBlock` `allowlist`) — see §6.
**Multi-device sync (plan: `PC/docs/plans/multi-device-sync.md`)**:
-- Write `<oauth_user_id>/manifest.json` from PC (any code path). The Server's `/sync/manifest/commit` is the **sole** writer; the CAS + size-delta quota check is server-side atomic. PC has STS scope `<oauth_user_id>/cloud/*` for writes — `manifest.json` is read-only for PC by design.
+- Write `private/<oauth_user_id>/manifest.json` from PC (any code path). The Server's `/sync/manifest/commit` is the **sole** writer; the CAS + size-delta quota check is server-side atomic. PC has STS scope `private/<oauth_user_id>/cloud/*` for writes — `manifest.json` is read-only for PC by design.
- Use the local 8-digit `uid` for the COS prefix. Cloud paths are scoped by **OAuth `user_id`**, not by the local container uid (same OAuth account on two machines = same cloud prefix, different local uids).
-- Bypass `features/sync/transport.ts` for any object under `<oauth_user_id>/`. Anyone touching the sync engine's bucket must go through that module (STS caching, gzip whitelist, multipart upload, rename optimization all live there).
+- Bypass `features/sync/transport.ts` for any object under `private/<oauth_user_id>/`. Anyone touching the sync engine's bucket must go through that module (STS caching, gzip whitelist, multipart upload, rename optimization all live there).
- Re-introduce a `codec.ts` abstraction in `features/sync/` (batch 3 decision: v1 ships no application-layer encryption; pre-emptive abstraction adds reading cost without value). v2 E2EE work is a clean re-introduction, not a re-edit.
- Set `Content-Encoding: gzip` on uploads — `cos-nodejs-sdk-v5` auto-decompresses on GET when that header is present, defeating the BYO-encoding contract (the goal is COS never decompresses). Use the custom `x-cos-meta-compressed: gzip` metadata + `Content-Type: application/gzip` per `transport.ts`.
- Treat manifest entry `size` as plaintext bytes — `size` is the **actual COS-stored byte count (compressed if compressed)** (batch 8). Quota tracking lives in `user_sync_usage.bytes` on the Server, also compressed.
@@ -456,13 +467,13 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
**Connectors (§6.5)**:
- Call `child_process.spawn` or instantiate an MCP transport outside `features/connectors/mcp-client.ts` (single spawn entry, mirrors the §1 CLI-agent rule).
- Bind a localhost listener outside `features/connectors/oauth.ts` (the §1 single documented exception — never extend it with other routes / reuse it for non-OAuth purposes).
-- Persist connector tokens to `<uid>/cloud/` — they're machine-private, MUST stay under `<uid>/local/config/connectors.json` (sync would propagate bearer material across devices the user didn't intend).
-- Write `connectors.json` / `connector-oauth.json` / `auth-profiles.json` as plaintext — every credential-bearing file under `<uid>/local/config/` goes through `util/crypto-vault.ts`. The legacy plaintext-read path is a one-shot migration affordance, NOT a fallback; never special-case a code path that emits plaintext.
+- Write a connector instance's `oauth_grant` / `dcr_client` / `transport` as plaintext fields in `connectors.json` — they belong inside the per-instance `secrets_enc` blob written by `registry.ts::_dehydrateSecrets` and decrypted by `_hydrateSecrets` (the envelope is plaintext; only the token-bearing blob is vault-sealed). `transport` goes in the blob even though it isn't a "secret" by name — `applyTemplate` bakes the resolved access_token into it. `connector-oauth.json` / `auth-profiles.json` stay whole-file vault-encrypted under `local/config/` with local-uid seeds (machine-private). Never emit plaintext credentials from any path.
- Reuse `features/account/` modules / `account.json` / `account.*` IPC namespace for connector auth — account login and connector authorization are two separate businesses (different Provider OAuth clients, different consent records, different revoke surfaces).
- Inject connector tools into the prompt via text — they reach the LLM through the SDK `tools[]` field, same path as native tools (§3).
- Treat `agent.enabled_connectors` like `agent.skill_list` — `undefined`/`[]` on connectors means "none allowed", NOT "no filter" (intentional asymmetry, per §6.5).
- Reintroduce flat per-tool injection of connector MCP actions into `runner.ts::buildRunner`'s `wrappedTools` — connectors go through the `## Connectors` system-prompt block + two umbrella meta-tools (`list_connector_tools` / `call_connector_tool`) by design (per §6.5). **Why**: the umbrella indirection is the entire point of dodging the 20–50 tool-selection-accuracy cliff and keeping the prompt-cache prefix stable across connect/disconnect events. If a high-frequency action seems to need direct exposure, that's a `list_connector_tools` discoverability problem (improve the action description) — NOT a license to fork a "pinned tool" second pathway. The single-pathway rule mirrors the group-chat dispatch rule (§9 "Build a new enqueue / scheduling function in parallel to bus.enqueue") — parallel paths dilute each other.
-- Expose connector meta-tools to a non-group-chat session — only `gconv` (commander) + `gmember` (agent worker) get them. `agent` (agent-edit) gets the `## Connectors` block ONLY (no tools — authoring sessions must not produce external side effects); `skill` / KB-image / CLI / reflect / memory-extract / anon get neither block nor tools. The single source is `runner.ts::_connectorExposure` (per §6.5 tri-state gate). Adding a new conversation kind that needs connector access requires extending this function explicitly + an entry in §5's session-id table.
+- Give `call_connector_tool` to a non-`gconv`/`gmember` session — only commander + agent worker get the executable tool. `agent` (agent-edit) gets `list_connector_tools` for schema discovery but NEVER `call_connector_tool` — authoring sessions must not produce external side effects. `skill` / KB-image / CLI / reflect / memory-extract / anon get neither block nor tools. The single source is `runner.ts::connectorExposureFromSessionId` (per §6.5 tri-state gate). Adding a new conversation kind that needs any connector access requires extending this function explicitly + an entry in §5's session-id table.
+- Reintroduce a status suffix (`— disconnected (ask user to refresh)`, `— error: …`) on the `## Connectors` block lines. `resolveVisibleConnectors` filters to `status.kind === 'connected'` so a non-connected instance is invisible to the LLM entirely (per §6.5 live-state filter). Showing a status hint the LLM can't act on mid-task is noise; the user resolves the state in the Connectors panel and the instance reappears on the next turn.
- Reintroduce a free-form "add custom MCP server" UI / IPC, or an API-key install path — every install goes through `connectViaOAuth(catalog_id)`. If a service isn't in the catalog, add the catalog row first; if it lacks OAuth, leave it out of the curated set.
**Group chat**:
diff --git a/bin/gcal-mcp-server.cjs b/bin/gcal-mcp-server.cjs
new file mode 100644
index 00000000..94143658
--- /dev/null
+++ b/bin/gcal-mcp-server.cjs
@@ -0,0 +1,364 @@
+#!/usr/bin/env node
+// Google Calendar MCP server (stdio). Same pattern as bin/gmail-mcp-server.cjs — wraps the public
+// Google Calendar REST API (`calendar.googleapis.com`, GA since 2014) to bypass the Workspace MCP
+// Developer Preview allowlist on `calendarmcp.googleapis.com`. OAuth scope `calendar` granted by
+// Server's `google.py::_SCOPES_BY_CATALOG_ID['gcal']`; token injected via `GOOGLE_ACCESS_TOKEN`.
+
+const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
+const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
+
+const TOKEN = process.env.GOOGLE_ACCESS_TOKEN || '';
+const BASE = 'https://www.googleapis.com/calendar/v3';
+const MAX_LIST = 50;
+
+const TOOLS = [
+ {
+ name: 'list_calendars',
+ description: 'List the user\'s calendars (the calendarId values feed `list_events` / `create_event`). `primary` is the user\'s default.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'list_events',
+ description:
+ 'List events on a calendar within a time window. Defaults: calendarId=primary, timeMin=now, ' +
+ 'timeMax=now+7d, maxResults=20 (max 50). `q` does free-text search across summary / description / ' +
+ 'attendees / location.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Calendar id from `list_calendars` (default "primary").' },
+ timeMin: { type: 'string', description: 'RFC3339 lower bound (default now).' },
+ timeMax: { type: 'string', description: 'RFC3339 upper bound (default now + 7d).' },
+ q: { type: 'string', description: 'Free-text query.' },
+ maxResults: { type: 'integer', minimum: 1, maximum: 50 },
+ },
+ },
+ },
+ {
+ name: 'get_event',
+ description: 'Fetch a single event by id.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Default "primary".' },
+ eventId: { type: 'string' },
+ },
+ required: ['eventId'],
+ },
+ },
+ {
+ name: 'create_event',
+ description:
+ 'Create a calendar event. `start` / `end` accept either { dateTime: RFC3339, timeZone? } for ' +
+ 'timed events or { date: YYYY-MM-DD } for all-day. `attendees` is a list of email strings.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Default "primary".' },
+ summary: { type: 'string', description: 'Event title.' },
+ start: { type: 'object', description: '{dateTime, timeZone?} OR {date}.' },
+ end: { type: 'object', description: 'Same shape as start.' },
+ attendees: { type: 'array', items: { type: 'string' }, description: 'Email list.' },
+ description: { type: 'string' },
+ location: { type: 'string' },
+ },
+ required: ['summary', 'start', 'end'],
+ },
+ },
+ {
+ name: 'quick_add_event',
+ description:
+ 'Create an event from a natural-language string ("Lunch with Sam tomorrow at noon"). Google parses ' +
+ 'date/time/attendees itself. Faster than `create_event` for one-shot inputs; less control over fields.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Default "primary".' },
+ text: { type: 'string', description: 'Natural-language event description.' },
+ },
+ required: ['text'],
+ },
+ },
+ {
+ name: 'update_event',
+ description:
+ 'Patch an event. Only fields you pass are touched (PATCH semantics). Use `move_event` to ' +
+ 'change the calendar.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Default "primary".' },
+ eventId: { type: 'string' },
+ summary: { type: 'string' },
+ start: { type: 'object', description: '{dateTime, timeZone?} OR {date}.' },
+ end: { type: 'object' },
+ attendees: { type: 'array', items: { type: 'string' } },
+ description: { type: 'string' },
+ location: { type: 'string' },
+ },
+ required: ['eventId'],
+ },
+ },
+ {
+ name: 'delete_event',
+ description: 'Delete an event. Irreversible.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Default "primary".' },
+ eventId: { type: 'string' },
+ },
+ required: ['eventId'],
+ },
+ },
+ {
+ name: 'move_event',
+ description: 'Move an event from one calendar to another (same time, different calendar).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Source calendar id.' },
+ eventId: { type: 'string' },
+ destinationCalendarId: { type: 'string', description: 'Where to move the event.' },
+ },
+ required: ['eventId', 'destinationCalendarId'],
+ },
+ },
+ {
+ name: 'list_event_instances',
+ description: 'Expand a recurring event into its individual instances within a time window.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string', description: 'Default "primary".' },
+ eventId: { type: 'string', description: 'The recurring event\'s base id.' },
+ timeMin: { type: 'string', description: 'RFC3339.' },
+ timeMax: { type: 'string', description: 'RFC3339.' },
+ maxResults: { type: 'integer', minimum: 1, maximum: 100 },
+ },
+ required: ['eventId'],
+ },
+ },
+ {
+ name: 'freebusy_query',
+ description:
+ 'Check free/busy slots for a set of calendars over a time window. Returns blocked time ranges per ' +
+ 'calendar — useful for "find a slot when everyone\'s free".',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ timeMin: { type: 'string', description: 'RFC3339 start.' },
+ timeMax: { type: 'string', description: 'RFC3339 end.' },
+ calendarIds: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Calendars or attendee emails to check.',
+ },
+ timeZone: { type: 'string', description: 'Optional IANA tz (e.g. "Asia/Shanghai").' },
+ },
+ required: ['timeMin', 'timeMax', 'calendarIds'],
+ },
+ },
+ {
+ name: 'create_calendar',
+ description: 'Create a new secondary calendar. Returns the new calendarId.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ summary: { type: 'string', description: 'Calendar name.' },
+ description: { type: 'string' },
+ timeZone: { type: 'string', description: 'IANA tz (default user\'s).' },
+ },
+ required: ['summary'],
+ },
+ },
+ {
+ name: 'delete_calendar',
+ description: 'Delete a secondary calendar (you can\'t delete `primary`). All events on it are removed.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ calendarId: { type: 'string' },
+ },
+ required: ['calendarId'],
+ },
+ },
+];
+
+async function gFetch(pathAndQuery, init) {
+ if (!TOKEN) throw new Error('GOOGLE_ACCESS_TOKEN env var not set');
+ const res = await fetch(`${BASE}${pathAndQuery}`, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${TOKEN}`,
+ Accept: 'application/json',
+ ...(init?.body ? { 'Content-Type': 'application/json' } : {}),
+ ...(init?.headers || {}),
+ },
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ let msg = text;
+ try { msg = JSON.parse(text).error?.message || text; } catch { /* keep raw */ }
+ throw new Error(`Calendar API ${res.status}: ${msg}`);
+ }
+ return text ? JSON.parse(text) : {};
+}
+
+async function callTool(name, args) {
+ if (name === 'list_calendars') {
+ const r = await gFetch('/users/me/calendarList');
+ return {
+ calendars: (r.items || []).map((c) => ({
+ id: c.id, summary: c.summary, primary: !!c.primary, accessRole: c.accessRole, timeZone: c.timeZone,
+ })),
+ };
+ }
+ if (name === 'list_events') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const now = new Date();
+ const timeMin = args.timeMin || now.toISOString();
+ const timeMax = args.timeMax || new Date(now.getTime() + 7 * 86400 * 1000).toISOString();
+ const max = Math.min(MAX_LIST, Math.max(1, parseInt(args.maxResults, 10) || 20));
+ const qs = new URLSearchParams({
+ timeMin, timeMax, maxResults: String(max), singleEvents: 'true', orderBy: 'startTime',
+ });
+ if (args.q) qs.set('q', String(args.q));
+ const r = await gFetch(`/calendars/${cid}/events?${qs}`);
+ return {
+ events: (r.items || []).map((e) => ({
+ id: e.id,
+ summary: e.summary,
+ start: e.start,
+ end: e.end,
+ location: e.location,
+ attendees: (e.attendees || []).map((a) => ({ email: a.email, responseStatus: a.responseStatus })),
+ htmlLink: e.htmlLink,
+ status: e.status,
+ })),
+ nextPageToken: r.nextPageToken,
+ };
+ }
+ if (name === 'get_event') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const eid = encodeURIComponent(String(args.eventId || ''));
+ if (!eid) throw new Error('eventId is required');
+ return await gFetch(`/calendars/${cid}/events/${eid}`);
+ }
+ if (name === 'create_event') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const body = {
+ summary: args.summary, start: args.start, end: args.end,
+ ...(args.description ? { description: args.description } : {}),
+ ...(args.location ? { location: args.location } : {}),
+ ...(Array.isArray(args.attendees) && args.attendees.length
+ ? { attendees: args.attendees.map((e) => ({ email: String(e) })) }
+ : {}),
+ };
+ const r = await gFetch(`/calendars/${cid}/events`, { method: 'POST', body: JSON.stringify(body) });
+ return { id: r.id, htmlLink: r.htmlLink, status: r.status, summary: r.summary, start: r.start, end: r.end };
+ }
+ if (name === 'quick_add_event') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const text = String(args.text || '').trim();
+ if (!text) throw new Error('text is required');
+ const r = await gFetch(`/calendars/${cid}/events/quickAdd?text=${encodeURIComponent(text)}`, { method: 'POST' });
+ return { id: r.id, htmlLink: r.htmlLink, summary: r.summary, start: r.start, end: r.end };
+ }
+ if (name === 'update_event') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const eid = encodeURIComponent(String(args.eventId || ''));
+ if (!eid) throw new Error('eventId is required');
+ const body = {};
+ if (typeof args.summary === 'string') body.summary = args.summary;
+ if (args.start) body.start = args.start;
+ if (args.end) body.end = args.end;
+ if (typeof args.description === 'string') body.description = args.description;
+ if (typeof args.location === 'string') body.location = args.location;
+ if (Array.isArray(args.attendees)) body.attendees = args.attendees.map((e) => ({ email: String(e) }));
+ const r = await gFetch(`/calendars/${cid}/events/${eid}`, { method: 'PATCH', body: JSON.stringify(body) });
+ return { id: r.id, htmlLink: r.htmlLink, summary: r.summary, start: r.start, end: r.end };
+ }
+ if (name === 'delete_event') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const eid = encodeURIComponent(String(args.eventId || ''));
+ if (!eid) throw new Error('eventId is required');
+ await gFetch(`/calendars/${cid}/events/${eid}`, { method: 'DELETE' });
+ return { ok: true };
+ }
+ if (name === 'move_event') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const eid = encodeURIComponent(String(args.eventId || ''));
+ const dest = encodeURIComponent(String(args.destinationCalendarId || ''));
+ if (!eid || !dest) throw new Error('eventId and destinationCalendarId are both required');
+ const r = await gFetch(`/calendars/${cid}/events/${eid}/move?destination=${dest}`, { method: 'POST' });
+ return { id: r.id, htmlLink: r.htmlLink, summary: r.summary };
+ }
+ if (name === 'list_event_instances') {
+ const cid = encodeURIComponent(args.calendarId || 'primary');
+ const eid = encodeURIComponent(String(args.eventId || ''));
+ if (!eid) throw new Error('eventId is required');
+ const max = Math.min(100, Math.max(1, parseInt(args.maxResults, 10) || 25));
+ const qs = new URLSearchParams({ maxResults: String(max) });
+ if (args.timeMin) qs.set('timeMin', String(args.timeMin));
+ if (args.timeMax) qs.set('timeMax', String(args.timeMax));
+ const r = await gFetch(`/calendars/${cid}/events/${eid}/instances?${qs}`);
+ return {
+ instances: (r.items || []).map((e) => ({
+ id: e.id, originalStartTime: e.originalStartTime, start: e.start, end: e.end, status: e.status,
+ })),
+ };
+ }
+ if (name === 'freebusy_query') {
+ if (!args.timeMin || !args.timeMax) throw new Error('timeMin and timeMax are required');
+ const ids = Array.isArray(args.calendarIds) ? args.calendarIds.filter((x) => typeof x === 'string') : [];
+ if (!ids.length) throw new Error('calendarIds is required (non-empty array)');
+ const body = {
+ timeMin: String(args.timeMin),
+ timeMax: String(args.timeMax),
+ items: ids.map((id) => ({ id })),
+ ...(args.timeZone ? { timeZone: String(args.timeZone) } : {}),
+ };
+ const r = await gFetch('/freeBusy', { method: 'POST', body: JSON.stringify(body) });
+ return { calendars: r.calendars || {}, timeMin: r.timeMin, timeMax: r.timeMax };
+ }
+ if (name === 'create_calendar') {
+ const summary = String(args.summary || '').trim();
+ if (!summary) throw new Error('summary is required');
+ const body = {
+ summary,
+ ...(args.description ? { description: String(args.description) } : {}),
+ ...(args.timeZone ? { timeZone: String(args.timeZone) } : {}),
+ };
+ const r = await gFetch('/calendars', { method: 'POST', body: JSON.stringify(body) });
+ return { id: r.id, summary: r.summary, timeZone: r.timeZone };
+ }
+ if (name === 'delete_calendar') {
+ const cid = encodeURIComponent(String(args.calendarId || ''));
+ if (!cid) throw new Error('calendarId is required');
+ await gFetch(`/calendars/${cid}`, { method: 'DELETE' });
+ return { ok: true };
+ }
+ throw new Error(`Unknown tool: ${name}`);
+}
+
+async function main() {
+ const server = new Server({ name: 'gcal-rest', version: '0.1.0' }, { capabilities: { tools: {} } });
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const { name, arguments: args = {} } = req.params;
+ try {
+ const result = await callTool(name, args || {});
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: (err && err.message) || String(err) }], isError: true };
+ }
+ });
+ await server.connect(new StdioServerTransport());
+}
+
+main().catch((err) => {
+ process.stderr.write(`gcal-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+});
diff --git a/bin/gdocs-mcp-server.cjs b/bin/gdocs-mcp-server.cjs
new file mode 100644
index 00000000..31ff5dda
--- /dev/null
+++ b/bin/gdocs-mcp-server.cjs
@@ -0,0 +1,263 @@
+#!/usr/bin/env node
+// Google Docs MCP server (stdio). Wraps `docs.googleapis.com` REST API.
+// V1: read full document + create empty doc. `update_document` deferred (batchUpdate's request[]
+// schema is complex; defer until we see real workflow demand).
+
+const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
+const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
+
+const TOKEN = process.env.GOOGLE_ACCESS_TOKEN || '';
+const BASE = 'https://docs.googleapis.com/v1';
+const MAX_BODY_BYTES = 16 * 1024; // Docs body cap (larger than Gmail's 8KB — docs are explicitly user-requested content)
+
+const TOOLS = [
+ {
+ name: 'get_document',
+ description:
+ 'Fetch a Google Docs document and return its plain-text body (paragraphs flattened, formatting ' +
+ 'discarded). Truncated to ~16KB; the full structured form is too noisy for LLM consumption — ' +
+ 'if a workflow needs styles / tables / images by region, file a follow-up to add a structured ' +
+ 'reader tool.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ documentId: {
+ type: 'string',
+ description: 'The Google Docs document id (the long hash in the URL after /document/d/).',
+ },
+ },
+ required: ['documentId'],
+ },
+ },
+ {
+ name: 'create_document',
+ description: 'Create a new empty Google Docs document. Returns the new documentId.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ title: { type: 'string', description: 'Title of the new document.' },
+ },
+ required: ['title'],
+ },
+ },
+ {
+ name: 'append_text',
+ description:
+ 'Append text to the end of a Google Doc — the most common write op. Adds a trailing newline ' +
+ 'unless your text already ends with one. Plain text only; styles / formatting not applied.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ documentId: { type: 'string' },
+ text: { type: 'string', description: 'Text to append.' },
+ },
+ required: ['documentId', 'text'],
+ },
+ },
+ {
+ name: 'insert_text',
+ description:
+ 'Insert text at a specific 1-based character index. For "add to the end" prefer `append_text`. ' +
+ 'Indices are tricky in Docs (each paragraph has a structural newline that counts) — try ' +
+ '`get_document` first to see the body, then count to the desired position.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ documentId: { type: 'string' },
+ index: { type: 'integer', minimum: 1, description: '1-based character index.' },
+ text: { type: 'string' },
+ },
+ required: ['documentId', 'index', 'text'],
+ },
+ },
+ {
+ name: 'replace_text',
+ description:
+ 'Find-and-replace text across the entire document. Returns the count of replacements made. Set ' +
+ '`matchCase: true` for case-sensitive matching (default false).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ documentId: { type: 'string' },
+ find: { type: 'string', description: 'Text to find.' },
+ replace: { type: 'string', description: 'Replacement text. Pass empty string to delete.' },
+ matchCase: { type: 'boolean' },
+ },
+ required: ['documentId', 'find', 'replace'],
+ },
+ },
+ {
+ name: 'get_document_outline',
+ description:
+ 'Get the heading structure of a document — for "show me what\'s in this doc" without reading ' +
+ 'the whole body. Returns each heading with its nesting level (1 = top-level, 2 = H2, etc.) and ' +
+ 'startIndex (usable with `insert_text`).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ documentId: { type: 'string' },
+ },
+ required: ['documentId'],
+ },
+ },
+];
+
+async function gFetch(pathAndQuery, init) {
+ if (!TOKEN) throw new Error('GOOGLE_ACCESS_TOKEN env var not set');
+ const res = await fetch(`${BASE}${pathAndQuery}`, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${TOKEN}`, Accept: 'application/json',
+ ...(init?.body ? { 'Content-Type': 'application/json' } : {}),
+ ...(init?.headers || {}),
+ },
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ let msg = text;
+ try { msg = JSON.parse(text).error?.message || text; } catch { /* keep raw */ }
+ throw new Error(`Docs API ${res.status}: ${msg}`);
+ }
+ return text ? JSON.parse(text) : {};
+}
+
+// Walk a Docs document body, concatenating every paragraph's textRun content. Skips lists /
+// tables / images — for the v1 "let the model read a doc" use case, prose is what matters.
+function _flattenBody(body) {
+ if (!body || !Array.isArray(body.content)) return '';
+ const chunks = [];
+ for (const el of body.content) {
+ if (el.paragraph?.elements) {
+ for (const part of el.paragraph.elements) {
+ if (part.textRun?.content) chunks.push(part.textRun.content);
+ }
+ }
+ if (el.table) chunks.push('\n[table omitted]\n');
+ // Skip sectionBreak / etc.
+ }
+ let out = chunks.join('').replace(/\n{3,}/g, '\n\n').trim();
+ let truncated = false;
+ if (Buffer.byteLength(out, 'utf8') > MAX_BODY_BYTES) {
+ out = Buffer.from(out, 'utf8').subarray(0, MAX_BODY_BYTES).toString('utf8') + '\n…[truncated]';
+ truncated = true;
+ }
+ return { text: out, truncated };
+}
+
+async function callTool(name, args) {
+ if (name === 'get_document') {
+ const id = encodeURIComponent(String(args.documentId || ''));
+ if (!id) throw new Error('documentId is required');
+ const doc = await gFetch(`/documents/${id}`);
+ const flat = _flattenBody(doc.body);
+ return {
+ documentId: doc.documentId,
+ title: doc.title,
+ revisionId: doc.revisionId,
+ body: flat.text,
+ ...(flat.truncated ? { bodyTruncated: true } : {}),
+ };
+ }
+ if (name === 'create_document') {
+ const title = String(args.title || '').trim();
+ if (!title) throw new Error('title is required');
+ const r = await gFetch('/documents', { method: 'POST', body: JSON.stringify({ title }) });
+ return { documentId: r.documentId, title: r.title };
+ }
+ if (name === 'append_text') {
+ const id = encodeURIComponent(String(args.documentId || ''));
+ const text = String(args.text || '');
+ if (!id) throw new Error('documentId is required');
+ if (!text) throw new Error('text is required');
+ // endOfSegmentLocation appends at the very end of the body; Google computes the index itself.
+ const r = await gFetch(`/documents/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({
+ requests: [{ insertText: { endOfSegmentLocation: {}, text } }],
+ }),
+ });
+ return { documentId: r.documentId, replies: (r.replies || []).length };
+ }
+ if (name === 'insert_text') {
+ const id = encodeURIComponent(String(args.documentId || ''));
+ const index = parseInt(args.index, 10);
+ const text = String(args.text || '');
+ if (!id) throw new Error('documentId is required');
+ if (!(index >= 1)) throw new Error('index must be a positive integer');
+ if (!text) throw new Error('text is required');
+ const r = await gFetch(`/documents/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({
+ requests: [{ insertText: { location: { index }, text } }],
+ }),
+ });
+ return { documentId: r.documentId, replies: (r.replies || []).length };
+ }
+ if (name === 'replace_text') {
+ const id = encodeURIComponent(String(args.documentId || ''));
+ if (!id) throw new Error('documentId is required');
+ const find = String(args.find || '');
+ if (!find) throw new Error('find is required');
+ const replace = String(args.replace ?? '');
+ const matchCase = args.matchCase === true;
+ const r = await gFetch(`/documents/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({
+ requests: [{
+ replaceAllText: {
+ containsText: { text: find, matchCase },
+ replaceText: replace,
+ },
+ }],
+ }),
+ });
+ const reply = (r.replies && r.replies[0]) || {};
+ return { documentId: r.documentId, replacements: reply.replaceAllText?.occurrencesChanged || 0 };
+ }
+ if (name === 'get_document_outline') {
+ const id = encodeURIComponent(String(args.documentId || ''));
+ if (!id) throw new Error('documentId is required');
+ const doc = await gFetch(`/documents/${id}`);
+ const headings = [];
+ for (const el of (doc.body?.content || [])) {
+ const p = el.paragraph;
+ if (!p) continue;
+ const style = p.paragraphStyle?.namedStyleType || '';
+ // Google's heading types: HEADING_1 .. HEADING_6, TITLE, SUBTITLE
+ const m = /^HEADING_(\d)$/.exec(style);
+ if (!m && style !== 'TITLE' && style !== 'SUBTITLE') continue;
+ const text = (p.elements || []).map((e) => e.textRun?.content || '').join('').replace(/\n+$/, '').trim();
+ if (!text) continue;
+ headings.push({
+ level: m ? parseInt(m[1], 10) : (style === 'TITLE' ? 0 : 1),
+ kind: style,
+ text,
+ startIndex: el.startIndex,
+ endIndex: el.endIndex,
+ });
+ }
+ return { documentId: doc.documentId, title: doc.title, headings };
+ }
+ throw new Error(`Unknown tool: ${name}`);
+}
+
+async function main() {
+ const server = new Server({ name: 'gdocs-rest', version: '0.1.0' }, { capabilities: { tools: {} } });
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const { name, arguments: args = {} } = req.params;
+ try {
+ const result = await callTool(name, args || {});
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: (err && err.message) || String(err) }], isError: true };
+ }
+ });
+ await server.connect(new StdioServerTransport());
+}
+
+main().catch((err) => {
+ process.stderr.write(`gdocs-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+});
diff --git a/bin/gmail-mcp-server.cjs b/bin/gmail-mcp-server.cjs
new file mode 100644
index 00000000..031c09c6
--- /dev/null
+++ b/bin/gmail-mcp-server.cjs
@@ -0,0 +1,659 @@
+#!/usr/bin/env node
+// Gmail MCP server (stdio) — wraps the public Gmail REST API behind the MCP tool-use
+// protocol. Spawned as a child process by `features/connectors/mcp-client.ts`; OAuth
+// access_token is injected through `GOOGLE_ACCESS_TOKEN` env (see `apply-template.ts`).
+//
+// Why this exists: Google's hosted `gmailmcp.googleapis.com` is in Developer Preview with a
+// project-level allowlist that third-party OAuth clients can't get on without enrollment in
+// the Workspace Developer Preview Program. The underlying Gmail REST API
+// (`gmail.googleapis.com`, GA since 2014) has no such gate, so we wrap it ourselves. The
+// catalog entry's transport_template references this script via the `${ORKAS_NODE}` +
+// `${ORKAS_PC_DIR}/bin/gmail-mcp-server.cjs` placeholder pair, which `apply-template.ts`
+// resolves to Electron's binary path running with `ELECTRON_RUN_AS_NODE=1` so we don't
+// require the user to have node on PATH.
+//
+// Tool surface (5 tools, v1):
+// - search_messages(query, maxResults?) → list of message ids + snippets + headers
+// - get_message(id, format?) → headers + body preview (full = decoded text, 8KB cap)
+// - list_labels() → user's Gmail labels
+// - send_message(to, subject, body, cc?, bcc?, threadId?) → builds RFC 2822 + base64url-encoded `raw` blob; threadId for replies
+// - modify_message_labels(id, addLabelIds?, removeLabelIds?) → archive (remove INBOX), mark read (remove UNREAD), star (add STARRED), etc.
+//
+// TODO (v2): get_attachment(messageId, attachmentId); html body in send_message.
+
+const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
+const {
+ ListToolsRequestSchema,
+ CallToolRequestSchema,
+} = require('@modelcontextprotocol/sdk/types.js');
+
+const TOKEN = process.env.GOOGLE_ACCESS_TOKEN || '';
+const BASE = 'https://gmail.googleapis.com/gmail/v1/users/me';
+const MAX_BODY_BYTES = 8 * 1024; // 8 KB cap on the decoded body text; attachments still show up as metadata-only
+
+// ── Tool definitions ──────────────────────────────────────────────────
+
+const TOOLS = [
+ {
+ name: 'search_messages',
+ description:
+ 'Search Gmail messages using Gmail query syntax (e.g. "in:inbox", "from:[email protected]", ' +
+ '"is:unread", "after:2024/01/01", combinations like "in:inbox is:unread"). Returns a list ' +
+ 'of messages with id, threadId, snippet, and key headers (From, Subject, Date). For full ' +
+ 'body, call `get_message` with the returned id.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Gmail search query syntax. Required.' },
+ maxResults: { type: 'integer', minimum: 1, maximum: 50, description: 'Default 10, max 50.' },
+ },
+ required: ['query'],
+ },
+ },
+ {
+ name: 'get_message',
+ description:
+ 'Fetch a single Gmail message. `format=metadata` (default) returns headers + snippet. ' +
+ '`format=full` adds the decoded body text (truncated to 8KB to keep model context manageable). ' +
+ 'Attachments are listed as metadata only (mime, filename, size, attachmentId) — call a ' +
+ 'dedicated download tool to fetch attachment bytes (not implemented in v1).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', description: 'Gmail message id (from search_messages).' },
+ format: {
+ type: 'string',
+ enum: ['minimal', 'metadata', 'full'],
+ description: 'Default metadata.',
+ },
+ },
+ required: ['id'],
+ },
+ },
+ {
+ name: 'list_labels',
+ description: 'List the user\'s Gmail labels. Useful for resolving label names to ids for filters.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'send_message',
+ description:
+ 'Send an email via the user\'s Gmail. v1 body is plain text only. Pass `threadId` to reply ' +
+ 'within an existing thread (the thread id is returned by `search_messages` / `get_message`). ' +
+ '`to` / `cc` / `bcc` accept either a single email string or an array of strings.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ to: { description: 'Recipient(s). String or array of strings.' },
+ subject: { type: 'string' },
+ body: { type: 'string', description: 'Plain-text body.' },
+ cc: { description: 'String or array of strings.' },
+ bcc: { description: 'String or array of strings.' },
+ threadId: { type: 'string', description: 'Reply within this thread.' },
+ },
+ required: ['to', 'subject', 'body'],
+ },
+ },
+ {
+ name: 'modify_message_labels',
+ description:
+ 'Add and/or remove labels on a message. Common system label ids: `INBOX` (remove to archive), ' +
+ '`UNREAD` (remove to mark as read; add to mark unread), `STARRED` (add to star), `SPAM`, `TRASH`, ' +
+ '`IMPORTANT`. Use `list_labels` for custom label ids. Returns the updated labelIds.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', description: 'Gmail message id.' },
+ addLabelIds: { type: 'array', items: { type: 'string' } },
+ removeLabelIds: { type: 'array', items: { type: 'string' } },
+ },
+ required: ['id'],
+ },
+ },
+ {
+ name: 'batch_modify_messages',
+ description: 'Add/remove labels on multiple messages in one call (e.g. archive 50 at once). Same label semantics as `modify_message_labels`.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ ids: { type: 'array', items: { type: 'string' }, description: 'Up to 1000 message ids.' },
+ addLabelIds: { type: 'array', items: { type: 'string' } },
+ removeLabelIds: { type: 'array', items: { type: 'string' } },
+ },
+ required: ['ids'],
+ },
+ },
+ {
+ name: 'trash_message',
+ description: 'Move a message to Trash. Reversible via `untrash_message` until Gmail empties trash (~30d).',
+ inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
+ },
+ {
+ name: 'untrash_message',
+ description: 'Restore a trashed message back to its prior labels.',
+ inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
+ },
+ {
+ name: 'list_threads',
+ description: 'Search at the thread level (returns thread ids + snippets). Same query syntax as `search_messages`. Use when the user asks about conversations rather than individual messages.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string' },
+ maxResults: { type: 'integer', minimum: 1, maximum: 50, description: 'Default 10, max 50.' },
+ },
+ required: ['query'],
+ },
+ },
+ {
+ name: 'get_thread',
+ description: 'Fetch a full Gmail thread — every message in the conversation, with their headers + snippets. `format=full` adds decoded body per message (each capped at 8KB).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', description: 'Thread id (from search/get_message or list_threads).' },
+ format: { type: 'string', enum: ['minimal', 'metadata', 'full'], description: 'Default metadata.' },
+ },
+ required: ['id'],
+ },
+ },
+ {
+ name: 'get_attachment',
+ description: 'Download an attachment as base64-encoded data. `messageId` + `attachmentId` come from `get_message` with `format=full`. Returns `{data: base64, size, mimeType}` — caller decodes if needed.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ messageId: { type: 'string' },
+ attachmentId: { type: 'string' },
+ },
+ required: ['messageId', 'attachmentId'],
+ },
+ },
+ {
+ name: 'list_drafts',
+ description: 'List drafts in the user\'s Gmail. Returns each draft\'s id + message metadata.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ maxResults: { type: 'integer', minimum: 1, maximum: 50, description: 'Default 20.' },
+ },
+ },
+ },
+ {
+ name: 'get_draft',
+ description: 'Fetch a single draft by id. `format=full` decodes the body (8KB cap).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string' },
+ format: { type: 'string', enum: ['minimal', 'metadata', 'full'] },
+ },
+ required: ['id'],
+ },
+ },
+ {
+ name: 'create_draft',
+ description: 'Save a new draft without sending. Same fields as `send_message` (to / subject / body / cc / bcc / threadId).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ to: {},
+ subject: { type: 'string' },
+ body: { type: 'string' },
+ cc: {},
+ bcc: {},
+ threadId: { type: 'string' },
+ },
+ required: ['to', 'subject', 'body'],
+ },
+ },
+ {
+ name: 'update_draft',
+ description: 'Replace a draft\'s content. All recipients / subject / body are overwritten (full replace, not patch).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string', description: 'Draft id.' },
+ to: {},
+ subject: { type: 'string' },
+ body: { type: 'string' },
+ cc: {},
+ bcc: {},
+ threadId: { type: 'string' },
+ },
+ required: ['id', 'to', 'subject', 'body'],
+ },
+ },
+ {
+ name: 'send_draft',
+ description: 'Send an existing draft. Returns the sent message id + threadId.',
+ inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
+ },
+ {
+ name: 'delete_draft',
+ description: 'Permanently delete a draft (not the same as trashing a sent message — drafts have no trash).',
+ inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
+ },
+ {
+ name: 'create_label',
+ description: 'Create a custom Gmail label. Returns the new label id (use it with `modify_message_labels`).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Label display name. Nested via slashes: "Work/Project A".' },
+ messageListVisibility: { type: 'string', enum: ['show', 'hide'] },
+ labelListVisibility: { type: 'string', enum: ['labelShow', 'labelShowIfUnread', 'labelHide'] },
+ },
+ required: ['name'],
+ },
+ },
+ {
+ name: 'update_label',
+ description: 'Rename or re-configure a custom label.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ id: { type: 'string' },
+ name: { type: 'string' },
+ messageListVisibility: { type: 'string', enum: ['show', 'hide'] },
+ labelListVisibility: { type: 'string', enum: ['labelShow', 'labelShowIfUnread', 'labelHide'] },
+ },
+ required: ['id'],
+ },
+ },
+ {
+ name: 'delete_label',
+ description: 'Permanently delete a custom label. Messages keep their content; this label is just removed from them.',
+ inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
+ },
+];
+
+// ── RFC 2822 helpers for send_message ─────────────────────────────────
+
+function _normalizeAddrs(v) {
+ if (Array.isArray(v)) return v.filter((x) => x && typeof x === 'string').map((x) => x.trim());
+ if (typeof v === 'string' && v.trim()) return [v.trim()];
+ return [];
+}
+
+// Per RFC 2047: non-ASCII header values → base64-encoded word `=?utf-8?B?...?=`. ASCII passthrough
+// keeps headers readable for English-only sends.
+// eslint-disable-next-line no-control-regex
+const _ASCII_ONLY = /^[\x00-\x7F]*$/;
+function _encodeHeader(s) {
+ return _ASCII_ONLY.test(s) ? s : `=?utf-8?B?${Buffer.from(s, 'utf8').toString('base64')}?=`;
+}
+
+function _b64urlEncode(bytes) {
+ return bytes.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+// Builds the `{raw, threadId?}` body shape used by both `messages.send` and `drafts` endpoints.
+// Plain-text v1; HTML body deferred. Centralized so send_message / create_draft / update_draft
+// produce identical wire format.
+function _buildRawMessage(args) {
+ const to = _normalizeAddrs(args.to);
+ if (!to.length) throw new Error('to is required (string or array of strings)');
+ const cc = _normalizeAddrs(args.cc);
+ const bcc = _normalizeAddrs(args.bcc);
+ const subject = String(args.subject || '');
+ const body = String(args.body || '');
+ const headers = [
+ `To: ${to.join(', ')}`,
+ ...(cc.length ? [`Cc: ${cc.join(', ')}`] : []),
+ ...(bcc.length ? [`Bcc: ${bcc.join(', ')}`] : []),
+ `Subject: ${_encodeHeader(subject)}`,
+ 'MIME-Version: 1.0',
+ 'Content-Type: text/plain; charset=UTF-8',
+ 'Content-Transfer-Encoding: 8bit',
+ ];
+ const rfc2822 = `${headers.join('\r\n')}\r\n\r\n${body}`;
+ return {
+ raw: _b64urlEncode(Buffer.from(rfc2822, 'utf8')),
+ ...(args.threadId ? { threadId: String(args.threadId) } : {}),
+ };
+}
+
+// ── HTTP helper ───────────────────────────────────────────────────────
+
+async function gmailFetch(pathAndQuery, init) {
+ if (!TOKEN) throw new Error('GOOGLE_ACCESS_TOKEN env var not set');
+ const url = `${BASE}${pathAndQuery}`;
+ const res = await fetch(url, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${TOKEN}`,
+ Accept: 'application/json',
+ ...(init?.body && !(init.headers || {})['Content-Type'] ? { 'Content-Type': 'application/json' } : {}),
+ ...(init?.headers || {}),
+ },
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ // Google's error shape: { error: { code, message, status } }. Surface message + status so
+ // the model can react (401 → reconnect, 403 → permissions, 429 → backoff).
+ let detail = text;
+ try { detail = JSON.parse(text).error?.message || text; } catch { /* keep raw */ }
+ throw new Error(`Gmail API ${res.status}: ${detail}`);
+ }
+ return text ? JSON.parse(text) : {};
+}
+
+// ── Body decoder (full format only) ───────────────────────────────────
+
+// Gmail returns message body as a tree of MIME parts. `body.data` is base64url-encoded. We
+// prefer text/plain over text/html, walk recursively, concatenate, truncate.
+function _b64urlDecode(s) {
+ if (!s) return '';
+ const padded = s.replace(/-/g, '+').replace(/_/g, '/');
+ return Buffer.from(padded, 'base64').toString('utf8');
+}
+
+function _extractBody(payload) {
+ if (!payload) return { text: '', attachments: [] };
+ const attachments = [];
+ const textChunks = [];
+ const htmlChunks = [];
+ const walk = (part) => {
+ if (!part) return;
+ const mime = part.mimeType || '';
+ const filename = part.filename || '';
+ const attachmentId = part.body?.attachmentId;
+ if (attachmentId) {
+ attachments.push({
+ attachmentId,
+ filename,
+ mimeType: mime,
+ size: part.body?.size || 0,
+ });
+ return;
+ }
+ if (mime === 'text/plain' && part.body?.data) textChunks.push(_b64urlDecode(part.body.data));
+ else if (mime === 'text/html' && part.body?.data) htmlChunks.push(_b64urlDecode(part.body.data));
+ if (Array.isArray(part.parts)) part.parts.forEach(walk);
+ };
+ walk(payload);
+ // Prefer plain text; fall back to HTML with rough tag strip (best-effort, not a full HTML parser).
+ let body = textChunks.join('\n\n');
+ if (!body && htmlChunks.length) {
+ body = htmlChunks
+ .join('\n\n')
+ .replace(/<\/?(script|style)[\s\S]*?>/gi, '') // drop script / style
+ .replace(/<[^>]+>/g, '') // strip remaining tags
+ .replace(/&nbsp;/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;/g, "'")
+ .replace(/\n{3,}/g, '\n\n');
+ }
+ let truncated = false;
+ if (Buffer.byteLength(body, 'utf8') > MAX_BODY_BYTES) {
+ body = Buffer.from(body, 'utf8').subarray(0, MAX_BODY_BYTES).toString('utf8') + '\n…[truncated to 8KB]';
+ truncated = true;
+ }
+ return { text: body, attachments, truncated };
+}
+
+function _headerMap(headers) {
+ const wanted = new Set(['from', 'to', 'cc', 'bcc', 'subject', 'date', 'reply-to', 'message-id']);
+ const out = {};
+ for (const h of headers || []) {
+ if (!h?.name) continue;
+ const k = h.name.toLowerCase();
+ if (wanted.has(k)) out[k] = h.value;
+ }
+ return out;
+}
+
+// ── Tool dispatch ─────────────────────────────────────────────────────
+
+async function callTool(name, args) {
+ if (name === 'search_messages') {
+ const q = String(args.query || '');
+ if (!q) throw new Error('query is required');
+ const max = Math.min(50, Math.max(1, parseInt(args.maxResults, 10) || 10));
+ const list = await gmailFetch(`/messages?q=${encodeURIComponent(q)}&maxResults=${max}`);
+ const ids = list.messages || [];
+ if (!ids.length) return { messages: [], resultSizeEstimate: list.resultSizeEstimate || 0 };
+ // Fetch metadata for each id in parallel. Limit concurrency at 8 to stay under Gmail's
+ // per-user-per-second quota (250) with margin.
+ const messages = [];
+ const queue = [...ids];
+ const workers = Math.min(8, queue.length);
+ async function pump() {
+ while (queue.length) {
+ const { id } = queue.shift();
+ const m = await gmailFetch(`/messages/${id}?format=metadata&metadataHeaders=From&metadataHeaders=To&metadataHeaders=Subject&metadataHeaders=Date`);
+ messages.push({
+ id: m.id,
+ threadId: m.threadId,
+ snippet: m.snippet || '',
+ labelIds: m.labelIds || [],
+ headers: _headerMap(m.payload?.headers),
+ });
+ }
+ }
+ await Promise.all(Array.from({ length: workers }, pump));
+ // Preserve search order from the list response (ids array is newest-first).
+ const order = new Map(ids.map((x, i) => [x.id, i]));
+ messages.sort((a, b) => order.get(a.id) - order.get(b.id));
+ return { messages, resultSizeEstimate: list.resultSizeEstimate || messages.length };
+ }
+ if (name === 'get_message') {
+ const id = String(args.id || '');
+ if (!id) throw new Error('id is required');
+ const format = ['minimal', 'metadata', 'full'].includes(args.format) ? args.format : 'metadata';
+ const m = await gmailFetch(`/messages/${id}?format=${format}`);
+ const out = {
+ id: m.id,
+ threadId: m.threadId,
+ snippet: m.snippet || '',
+ labelIds: m.labelIds || [],
+ sizeEstimate: m.sizeEstimate,
+ historyId: m.historyId,
+ internalDate: m.internalDate,
+ headers: _headerMap(m.payload?.headers),
+ };
+ if (format === 'full') {
+ const decoded = _extractBody(m.payload);
+ out.body = decoded.text;
+ out.attachments = decoded.attachments;
+ if (decoded.truncated) out.bodyTruncated = true;
+ }
+ return out;
+ }
+ if (name === 'list_labels') {
+ const r = await gmailFetch('/labels');
+ return {
+ labels: (r.labels || []).map((l) => ({
+ id: l.id,
+ name: l.name,
+ type: l.type,
+ messageListVisibility: l.messageListVisibility,
+ labelListVisibility: l.labelListVisibility,
+ })),
+ };
+ }
+ if (name === 'send_message') {
+ const body = _buildRawMessage(args);
+ const r = await gmailFetch('/messages/send', { method: 'POST', body: JSON.stringify(body) });
+ return { id: r.id, threadId: r.threadId, labelIds: r.labelIds };
+ }
+ if (name === 'modify_message_labels') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const addLabelIds = Array.isArray(args.addLabelIds) ? args.addLabelIds.filter((x) => typeof x === 'string') : [];
+ const removeLabelIds = Array.isArray(args.removeLabelIds) ? args.removeLabelIds.filter((x) => typeof x === 'string') : [];
+ if (!addLabelIds.length && !removeLabelIds.length) throw new Error('at least one of addLabelIds / removeLabelIds is required');
+ const r = await gmailFetch(`/messages/${id}/modify`, { method: 'POST', body: JSON.stringify({ addLabelIds, removeLabelIds }) });
+ return { id: r.id, threadId: r.threadId, labelIds: r.labelIds };
+ }
+ if (name === 'batch_modify_messages') {
+ const ids = Array.isArray(args.ids) ? args.ids.filter((x) => typeof x === 'string') : [];
+ if (!ids.length) throw new Error('ids is required (non-empty array)');
+ const addLabelIds = Array.isArray(args.addLabelIds) ? args.addLabelIds.filter((x) => typeof x === 'string') : [];
+ const removeLabelIds = Array.isArray(args.removeLabelIds) ? args.removeLabelIds.filter((x) => typeof x === 'string') : [];
+ if (!addLabelIds.length && !removeLabelIds.length) throw new Error('at least one of addLabelIds / removeLabelIds is required');
+ // batchModify endpoint returns 204 No Content on success → empty body.
+ await gmailFetch('/messages/batchModify', { method: 'POST', body: JSON.stringify({ ids, addLabelIds, removeLabelIds }) });
+ return { ok: true, modified: ids.length };
+ }
+ if (name === 'trash_message') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const r = await gmailFetch(`/messages/${id}/trash`, { method: 'POST' });
+ return { id: r.id, labelIds: r.labelIds };
+ }
+ if (name === 'untrash_message') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const r = await gmailFetch(`/messages/${id}/untrash`, { method: 'POST' });
+ return { id: r.id, labelIds: r.labelIds };
+ }
+ if (name === 'list_threads') {
+ const q = String(args.query || '');
+ if (!q) throw new Error('query is required');
+ const max = Math.min(50, Math.max(1, parseInt(args.maxResults, 10) || 10));
+ const r = await gmailFetch(`/threads?q=${encodeURIComponent(q)}&maxResults=${max}`);
+ return {
+ threads: (r.threads || []).map((t) => ({ id: t.id, snippet: t.snippet, historyId: t.historyId })),
+ resultSizeEstimate: r.resultSizeEstimate || (r.threads || []).length,
+ };
+ }
+ if (name === 'get_thread') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const format = ['minimal', 'metadata', 'full'].includes(args.format) ? args.format : 'metadata';
+ const r = await gmailFetch(`/threads/${id}?format=${format}`);
+ const messages = (r.messages || []).map((m) => {
+ const base = {
+ id: m.id, snippet: m.snippet, labelIds: m.labelIds || [],
+ internalDate: m.internalDate, headers: _headerMap(m.payload?.headers),
+ };
+ if (format === 'full') {
+ const decoded = _extractBody(m.payload);
+ base.body = decoded.text;
+ base.attachments = decoded.attachments;
+ if (decoded.truncated) base.bodyTruncated = true;
+ }
+ return base;
+ });
+ return { id: r.id, historyId: r.historyId, messages };
+ }
+ if (name === 'get_attachment') {
+ const mid = encodeURIComponent(String(args.messageId || ''));
+ const aid = encodeURIComponent(String(args.attachmentId || ''));
+ if (!mid || !aid) throw new Error('messageId and attachmentId are both required');
+ const r = await gmailFetch(`/messages/${mid}/attachments/${aid}`);
+ // Google's attachment endpoint returns `{size, data: base64url}`. Re-encode to standard base64
+ // for downstream consumption (most decoders want standard b64).
+ const std = (r.data || '').replace(/-/g, '+').replace(/_/g, '/');
+ return { data: std, size: r.size, encoding: 'base64' };
+ }
+ if (name === 'list_drafts') {
+ const max = Math.min(50, Math.max(1, parseInt(args.maxResults, 10) || 20));
+ const r = await gmailFetch(`/drafts?maxResults=${max}`);
+ return { drafts: (r.drafts || []).map((d) => ({ id: d.id, messageId: d.message?.id, threadId: d.message?.threadId })) };
+ }
+ if (name === 'get_draft') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const format = ['minimal', 'metadata', 'full'].includes(args.format) ? args.format : 'metadata';
+ const r = await gmailFetch(`/drafts/${id}?format=${format}`);
+ const m = r.message || {};
+ const out = {
+ id: r.id, messageId: m.id, threadId: m.threadId,
+ snippet: m.snippet, headers: _headerMap(m.payload?.headers),
+ };
+ if (format === 'full') {
+ const decoded = _extractBody(m.payload);
+ out.body = decoded.text;
+ out.attachments = decoded.attachments;
+ if (decoded.truncated) out.bodyTruncated = true;
+ }
+ return out;
+ }
+ if (name === 'create_draft') {
+ const message = _buildRawMessage(args);
+ const r = await gmailFetch('/drafts', { method: 'POST', body: JSON.stringify({ message }) });
+ return { id: r.id, messageId: r.message?.id, threadId: r.message?.threadId };
+ }
+ if (name === 'update_draft') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const message = _buildRawMessage(args);
+ const r = await gmailFetch(`/drafts/${id}`, { method: 'PUT', body: JSON.stringify({ message }) });
+ return { id: r.id, messageId: r.message?.id, threadId: r.message?.threadId };
+ }
+ if (name === 'send_draft') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const r = await gmailFetch('/drafts/send', { method: 'POST', body: JSON.stringify({ id: args.id }) });
+ return { id: r.id, threadId: r.threadId, labelIds: r.labelIds };
+ }
+ if (name === 'delete_draft') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ await gmailFetch(`/drafts/${id}`, { method: 'DELETE' });
+ return { ok: true };
+ }
+ if (name === 'create_label') {
+ const lbl = String(args.name || '').trim();
+ if (!lbl) throw new Error('name is required');
+ const body = {
+ name: lbl,
+ ...(args.messageListVisibility ? { messageListVisibility: args.messageListVisibility } : {}),
+ ...(args.labelListVisibility ? { labelListVisibility: args.labelListVisibility } : {}),
+ };
+ const r = await gmailFetch('/labels', { method: 'POST', body: JSON.stringify(body) });
+ return { id: r.id, name: r.name, type: r.type };
+ }
+ if (name === 'update_label') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ const body = {};
+ if (typeof args.name === 'string') body.name = args.name;
+ if (args.messageListVisibility) body.messageListVisibility = args.messageListVisibility;
+ if (args.labelListVisibility) body.labelListVisibility = args.labelListVisibility;
+ const r = await gmailFetch(`/labels/${id}`, { method: 'PATCH', body: JSON.stringify(body) });
+ return { id: r.id, name: r.name, type: r.type };
+ }
+ if (name === 'delete_label') {
+ const id = encodeURIComponent(String(args.id || ''));
+ if (!id) throw new Error('id is required');
+ await gmailFetch(`/labels/${id}`, { method: 'DELETE' });
+ return { ok: true };
+ }
+ throw new Error(`Unknown tool: ${name}`);
+}
+
+// ── MCP server wiring ─────────────────────────────────────────────────
+
+async function main() {
+ const server = new Server({ name: 'gmail-rest', version: '0.1.0' }, { capabilities: { tools: {} } });
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
+
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const { name, arguments: args = {} } = req.params;
+ try {
+ const result = await callTool(name, args || {});
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ const msg = (err && err.message) || String(err);
+ return { content: [{ type: 'text', text: msg }], isError: true };
+ }
+ });
+
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+}
+
+main().catch((err) => {
+ // Last-resort log to stderr; PC's main process tails this when diagnosing spawn failures.
+ process.stderr.write(`gmail-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+});
diff --git a/bin/gsheets-mcp-server.cjs b/bin/gsheets-mcp-server.cjs
new file mode 100644
index 00000000..778ea1ec
--- /dev/null
+++ b/bin/gsheets-mcp-server.cjs
@@ -0,0 +1,399 @@
+#!/usr/bin/env node
+// Google Sheets MCP server (stdio). Wraps `sheets.googleapis.com` v4.
+
+const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
+const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
+
+const TOKEN = process.env.GOOGLE_ACCESS_TOKEN || '';
+const BASE = 'https://sheets.googleapis.com/v4';
+
+const TOOLS = [
+ {
+ name: 'list_sheets',
+ description: 'List the tabs (sheets) in a spreadsheet. Returns each tab\'s sheetId, title, and dimensions.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string', description: 'The long hash in the URL after /spreadsheets/d/.' },
+ },
+ required: ['spreadsheetId'],
+ },
+ },
+ {
+ name: 'read_sheet',
+ description:
+ 'Read cell values from a range. `range` uses A1 notation: "Sheet1!A1:C10", "A1:B5" (first tab), ' +
+ '"Sheet1" (entire tab). `valueRenderOption=FORMATTED_VALUE` (default) returns user-visible strings; ' +
+ 'use `UNFORMATTED_VALUE` for raw numbers / serial dates; `FORMULA` to see formulas.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ range: { type: 'string', description: 'A1 notation.' },
+ valueRenderOption: { type: 'string', enum: ['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA'] },
+ },
+ required: ['spreadsheetId', 'range'],
+ },
+ },
+ {
+ name: 'write_sheet',
+ description:
+ 'Write cell values. `values` is a 2D array of cells (rows of values). `valueInputOption` controls ' +
+ 'how user input is parsed: `RAW` stores strings verbatim, `USER_ENTERED` parses formulas / dates ' +
+ 'like typing in the UI (default).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ range: { type: 'string', description: 'A1 notation — anchor for the write.' },
+ values: {
+ type: 'array',
+ description: 'Rows of cell values, e.g. [["a", 1], ["b", 2]].',
+ items: { type: 'array' },
+ },
+ valueInputOption: { type: 'string', enum: ['RAW', 'USER_ENTERED'] },
+ },
+ required: ['spreadsheetId', 'range', 'values'],
+ },
+ },
+ {
+ name: 'create_spreadsheet',
+ description: 'Create a new empty spreadsheet. Returns spreadsheetId + spreadsheetUrl.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ title: { type: 'string', description: 'Title of the new spreadsheet.' },
+ },
+ required: ['title'],
+ },
+ },
+ {
+ name: 'append_sheet',
+ description:
+ 'Append rows to the end of a sheet. Google detects the existing data table starting at `range` ' +
+ 'and appends after the last row. Common pattern: `range="Sheet1!A1"` lets Google find the table.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ range: { type: 'string', description: 'A1 notation. Google appends below the table at this anchor.' },
+ values: { type: 'array', description: '2D array of row values.', items: { type: 'array' } },
+ valueInputOption: { type: 'string', enum: ['RAW', 'USER_ENTERED'] },
+ },
+ required: ['spreadsheetId', 'range', 'values'],
+ },
+ },
+ {
+ name: 'clear_sheet',
+ description: 'Clear cell values in a range. Formatting + structure (rows/columns) untouched.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ range: { type: 'string', description: 'A1 notation.' },
+ },
+ required: ['spreadsheetId', 'range'],
+ },
+ },
+ {
+ name: 'batch_get',
+ description: 'Read values from multiple ranges at once. Returns one entry per range with the same `valueRenderOption`.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ ranges: { type: 'array', items: { type: 'string' }, description: 'A1 notation array.' },
+ valueRenderOption: { type: 'string', enum: ['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA'] },
+ },
+ required: ['spreadsheetId', 'ranges'],
+ },
+ },
+ {
+ name: 'batch_update_values',
+ description: 'Write multiple ranges in one call. `data` is an array of `{range, values}` objects.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ data: {
+ type: 'array',
+ description: 'Each entry: {range: A1, values: 2D array}.',
+ items: { type: 'object' },
+ },
+ valueInputOption: { type: 'string', enum: ['RAW', 'USER_ENTERED'] },
+ },
+ required: ['spreadsheetId', 'data'],
+ },
+ },
+ {
+ name: 'add_sheet',
+ description: 'Add a new tab (sheet) to an existing spreadsheet.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ title: { type: 'string', description: 'New sheet title.' },
+ index: { type: 'integer', description: 'Position index (0-based). Default appends.' },
+ rowCount: { type: 'integer' },
+ columnCount: { type: 'integer' },
+ },
+ required: ['spreadsheetId', 'title'],
+ },
+ },
+ {
+ name: 'delete_sheet',
+ description: 'Delete a tab (sheet) from a spreadsheet. Irreversible. Get `sheetId` from `list_sheets`.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ sheetId: { type: 'integer', description: 'The tab\'s sheetId (NOT title) — from `list_sheets`.' },
+ },
+ required: ['spreadsheetId', 'sheetId'],
+ },
+ },
+ {
+ name: 'duplicate_sheet',
+ description: 'Copy a tab within the same spreadsheet (or to a different spreadsheet via `destinationSpreadsheetId`).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ sheetId: { type: 'integer', description: 'Source tab\'s sheetId.' },
+ newSheetName: { type: 'string', description: 'Optional new title.' },
+ insertSheetIndex: { type: 'integer', description: 'Position of the copy (default: right after source).' },
+ },
+ required: ['spreadsheetId', 'sheetId'],
+ },
+ },
+ {
+ name: 'find_and_replace',
+ description: 'Find and replace text across an entire spreadsheet (or scoped to a single sheet / range). Returns occurrences changed.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ spreadsheetId: { type: 'string' },
+ find: { type: 'string' },
+ replacement: { type: 'string' },
+ matchCase: { type: 'boolean' },
+ matchEntireCell: { type: 'boolean' },
+ searchByRegex: { type: 'boolean' },
+ sheetId: { type: 'integer', description: 'Scope to one tab.' },
+ range: { type: 'string', description: 'A1 notation. Scope to one range.' },
+ },
+ required: ['spreadsheetId', 'find', 'replacement'],
+ },
+ },
+];
+
+async function gFetch(pathAndQuery, init) {
+ if (!TOKEN) throw new Error('GOOGLE_ACCESS_TOKEN env var not set');
+ const res = await fetch(`${BASE}${pathAndQuery}`, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${TOKEN}`, Accept: 'application/json',
+ ...(init?.body ? { 'Content-Type': 'application/json' } : {}),
+ ...(init?.headers || {}),
+ },
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ let msg = text;
+ try { msg = JSON.parse(text).error?.message || text; } catch { /* keep raw */ }
+ throw new Error(`Sheets API ${res.status}: ${msg}`);
+ }
+ return text ? JSON.parse(text) : {};
+}
+
+async function callTool(name, args) {
+ if (name === 'list_sheets') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ if (!id) throw new Error('spreadsheetId is required');
+ // fields= trims response — we only need sheet metadata, not cell data.
+ const r = await gFetch(`/spreadsheets/${id}?fields=properties(title),sheets.properties`);
+ return {
+ title: r.properties?.title,
+ sheets: (r.sheets || []).map((s) => ({
+ sheetId: s.properties?.sheetId,
+ title: s.properties?.title,
+ index: s.properties?.index,
+ rowCount: s.properties?.gridProperties?.rowCount,
+ columnCount: s.properties?.gridProperties?.columnCount,
+ })),
+ };
+ }
+ if (name === 'read_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ const range = String(args.range || '');
+ if (!id || !range) throw new Error('spreadsheetId and range are both required');
+ const opt = ['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA'].includes(args.valueRenderOption)
+ ? args.valueRenderOption : 'FORMATTED_VALUE';
+ const r = await gFetch(`/spreadsheets/${id}/values/${encodeURIComponent(range)}?valueRenderOption=${opt}`);
+ return { range: r.range, majorDimension: r.majorDimension, values: r.values || [] };
+ }
+ if (name === 'write_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ const range = String(args.range || '');
+ if (!id || !range) throw new Error('spreadsheetId and range are both required');
+ if (!Array.isArray(args.values)) throw new Error('values must be a 2D array');
+ const opt = ['RAW', 'USER_ENTERED'].includes(args.valueInputOption) ? args.valueInputOption : 'USER_ENTERED';
+ const r = await gFetch(
+ `/spreadsheets/${id}/values/${encodeURIComponent(range)}?valueInputOption=${opt}`,
+ { method: 'PUT', body: JSON.stringify({ values: args.values }) },
+ );
+ return {
+ updatedRange: r.updatedRange, updatedRows: r.updatedRows,
+ updatedColumns: r.updatedColumns, updatedCells: r.updatedCells,
+ };
+ }
+ if (name === 'create_spreadsheet') {
+ const title = String(args.title || '').trim();
+ if (!title) throw new Error('title is required');
+ const r = await gFetch('/spreadsheets', { method: 'POST', body: JSON.stringify({ properties: { title } }) });
+ return { spreadsheetId: r.spreadsheetId, spreadsheetUrl: r.spreadsheetUrl, title: r.properties?.title };
+ }
+ if (name === 'append_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ const range = String(args.range || '');
+ if (!id || !range) throw new Error('spreadsheetId and range are both required');
+ if (!Array.isArray(args.values)) throw new Error('values must be a 2D array');
+ const opt = ['RAW', 'USER_ENTERED'].includes(args.valueInputOption) ? args.valueInputOption : 'USER_ENTERED';
+ const r = await gFetch(
+ `/spreadsheets/${id}/values/${encodeURIComponent(range)}:append?valueInputOption=${opt}&insertDataOption=INSERT_ROWS`,
+ { method: 'POST', body: JSON.stringify({ values: args.values }) },
+ );
+ return {
+ updates: {
+ updatedRange: r.updates?.updatedRange,
+ updatedRows: r.updates?.updatedRows,
+ updatedColumns: r.updates?.updatedColumns,
+ updatedCells: r.updates?.updatedCells,
+ },
+ };
+ }
+ if (name === 'clear_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ const range = String(args.range || '');
+ if (!id || !range) throw new Error('spreadsheetId and range are both required');
+ const r = await gFetch(`/spreadsheets/${id}/values/${encodeURIComponent(range)}:clear`, { method: 'POST' });
+ return { clearedRange: r.clearedRange };
+ }
+ if (name === 'batch_get') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ const ranges = Array.isArray(args.ranges) ? args.ranges.filter((x) => typeof x === 'string') : [];
+ if (!id || !ranges.length) throw new Error('spreadsheetId and ranges are both required');
+ const opt = ['FORMATTED_VALUE', 'UNFORMATTED_VALUE', 'FORMULA'].includes(args.valueRenderOption)
+ ? args.valueRenderOption : 'FORMATTED_VALUE';
+ const qs = new URLSearchParams({ valueRenderOption: opt });
+ for (const r of ranges) qs.append('ranges', r);
+ const r = await gFetch(`/spreadsheets/${id}/values:batchGet?${qs}`);
+ return { valueRanges: r.valueRanges || [] };
+ }
+ if (name === 'batch_update_values') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ if (!id) throw new Error('spreadsheetId is required');
+ const data = Array.isArray(args.data) ? args.data : [];
+ if (!data.length) throw new Error('data is required (non-empty array)');
+ const opt = ['RAW', 'USER_ENTERED'].includes(args.valueInputOption) ? args.valueInputOption : 'USER_ENTERED';
+ const r = await gFetch(`/spreadsheets/${id}/values:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({ valueInputOption: opt, data }),
+ });
+ return {
+ totalUpdatedRows: r.totalUpdatedRows, totalUpdatedColumns: r.totalUpdatedColumns,
+ totalUpdatedCells: r.totalUpdatedCells, totalUpdatedSheets: r.totalUpdatedSheets,
+ };
+ }
+ if (name === 'add_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ const title = String(args.title || '').trim();
+ if (!id || !title) throw new Error('spreadsheetId and title are both required');
+ const properties = { title };
+ if (Number.isInteger(args.index)) properties.index = args.index;
+ if (Number.isInteger(args.rowCount) || Number.isInteger(args.columnCount)) {
+ properties.gridProperties = {
+ ...(Number.isInteger(args.rowCount) ? { rowCount: args.rowCount } : {}),
+ ...(Number.isInteger(args.columnCount) ? { columnCount: args.columnCount } : {}),
+ };
+ }
+ const r = await gFetch(`/spreadsheets/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({ requests: [{ addSheet: { properties } }] }),
+ });
+ const reply = r.replies?.[0]?.addSheet?.properties || {};
+ return { sheetId: reply.sheetId, title: reply.title, index: reply.index };
+ }
+ if (name === 'delete_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ if (!id) throw new Error('spreadsheetId is required');
+ if (!Number.isInteger(args.sheetId)) throw new Error('sheetId is required (integer)');
+ await gFetch(`/spreadsheets/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({ requests: [{ deleteSheet: { sheetId: args.sheetId } }] }),
+ });
+ return { ok: true };
+ }
+ if (name === 'duplicate_sheet') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ if (!id) throw new Error('spreadsheetId is required');
+ if (!Number.isInteger(args.sheetId)) throw new Error('sheetId is required (integer)');
+ const dup = { sourceSheetId: args.sheetId };
+ if (typeof args.newSheetName === 'string') dup.newSheetName = args.newSheetName;
+ if (Number.isInteger(args.insertSheetIndex)) dup.insertSheetIndex = args.insertSheetIndex;
+ const r = await gFetch(`/spreadsheets/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({ requests: [{ duplicateSheet: dup }] }),
+ });
+ const reply = r.replies?.[0]?.duplicateSheet?.properties || {};
+ return { sheetId: reply.sheetId, title: reply.title, index: reply.index };
+ }
+ if (name === 'find_and_replace') {
+ const id = encodeURIComponent(String(args.spreadsheetId || ''));
+ if (!id) throw new Error('spreadsheetId is required');
+ const find = String(args.find || '');
+ if (!find) throw new Error('find is required');
+ const fr = {
+ find,
+ replacement: String(args.replacement ?? ''),
+ matchCase: args.matchCase === true,
+ matchEntireCell: args.matchEntireCell === true,
+ searchByRegex: args.searchByRegex === true,
+ };
+ if (Number.isInteger(args.sheetId)) fr.sheetId = args.sheetId;
+ else if (typeof args.range === 'string' && args.range) fr.range = { sheetId: 0 }; // simplified — range scoping needs gridrange parsing; default to first sheet
+ else fr.allSheets = true;
+ const r = await gFetch(`/spreadsheets/${id}:batchUpdate`, {
+ method: 'POST',
+ body: JSON.stringify({ requests: [{ findReplace: fr }] }),
+ });
+ const reply = r.replies?.[0]?.findReplace || {};
+ return {
+ occurrencesChanged: reply.occurrencesChanged || 0,
+ valuesChanged: reply.valuesChanged || 0,
+ rowsChanged: reply.rowsChanged || 0,
+ sheetsChanged: reply.sheetsChanged || 0,
+ };
+ }
+ throw new Error(`Unknown tool: ${name}`);
+}
+
+async function main() {
+ const server = new Server({ name: 'gsheets-rest', version: '0.1.0' }, { capabilities: { tools: {} } });
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const { name, arguments: args = {} } = req.params;
+ try {
+ const result = await callTool(name, args || {});
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: (err && err.message) || String(err) }], isError: true };
+ }
+ });
+ await server.connect(new StdioServerTransport());
+}
+
+main().catch((err) => {
+ process.stderr.write(`gsheets-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+});
diff --git a/bin/gtasks-mcp-server.cjs b/bin/gtasks-mcp-server.cjs
new file mode 100644
index 00000000..a371100b
--- /dev/null
+++ b/bin/gtasks-mcp-server.cjs
@@ -0,0 +1,308 @@
+#!/usr/bin/env node
+// Google Tasks MCP server (stdio). Wraps `tasks.googleapis.com` v1.
+
+const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
+const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
+const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
+
+const TOKEN = process.env.GOOGLE_ACCESS_TOKEN || '';
+const BASE = 'https://tasks.googleapis.com/tasks/v1';
+const MAX_LIST = 100;
+
+const TOOLS = [
+ {
+ name: 'list_tasklists',
+ description: 'List the user\'s task lists. The default tasklist id is "@default".',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'list_tasks',
+ description:
+ 'List tasks in a tasklist. Default tasklist is "@default". `showCompleted=false` (default) hides ' +
+ 'finished tasks; set true to include them.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Tasklist id from `list_tasklists` (default "@default").' },
+ maxResults: { type: 'integer', minimum: 1, maximum: 100 },
+ showCompleted: { type: 'boolean' },
+ },
+ },
+ },
+ {
+ name: 'create_task',
+ description: 'Create a new task in a tasklist.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Default "@default".' },
+ title: { type: 'string' },
+ notes: { type: 'string' },
+ due: { type: 'string', description: 'RFC3339 timestamp (only the date portion is used by Google).' },
+ },
+ required: ['title'],
+ },
+ },
+ {
+ name: 'update_task',
+ description:
+ 'Update an existing task. `completed: true` marks it done (and `status` flips to "completed"). ' +
+ 'Only fields you pass are touched.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Default "@default".' },
+ taskId: { type: 'string' },
+ title: { type: 'string' },
+ notes: { type: 'string' },
+ due: { type: 'string', description: 'RFC3339.' },
+ completed: { type: 'boolean' },
+ },
+ required: ['taskId'],
+ },
+ },
+ {
+ name: 'get_task',
+ description: 'Fetch a single task by id.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Default "@default".' },
+ taskId: { type: 'string' },
+ },
+ required: ['taskId'],
+ },
+ },
+ {
+ name: 'delete_task',
+ description: 'Permanently delete a task. Irreversible.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Default "@default".' },
+ taskId: { type: 'string' },
+ },
+ required: ['taskId'],
+ },
+ },
+ {
+ name: 'move_task',
+ description:
+ 'Reorder or nest a task. `parent` makes it a subtask of that task id (omit to keep top-level). ' +
+ '`previous` places it after that sibling task (omit to put first).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Default "@default".' },
+ taskId: { type: 'string' },
+ parent: { type: 'string', description: 'Parent task id (omit = top-level).' },
+ previous: { type: 'string', description: 'Sibling-before task id (omit = first in list).' },
+ },
+ required: ['taskId'],
+ },
+ },
+ {
+ name: 'clear_completed',
+ description: 'Hide all completed tasks in a tasklist (Google\'s "clear" — marks them hidden, they still exist in the data).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Default "@default".' },
+ },
+ },
+ },
+ {
+ name: 'get_tasklist',
+ description: 'Fetch metadata for a single tasklist by id.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string', description: 'Tasklist id (use "@default" for the primary one).' },
+ },
+ required: ['tasklist'],
+ },
+ },
+ {
+ name: 'create_tasklist',
+ description: 'Create a new tasklist (a separate "list of tasks" — like a folder).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ title: { type: 'string', description: 'Tasklist title.' },
+ },
+ required: ['title'],
+ },
+ },
+ {
+ name: 'update_tasklist',
+ description: 'Rename a tasklist.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string' },
+ title: { type: 'string' },
+ },
+ required: ['tasklist', 'title'],
+ },
+ },
+ {
+ name: 'delete_tasklist',
+ description: 'Delete a tasklist along with all its tasks. Irreversible. Can\'t delete the default tasklist.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ tasklist: { type: 'string' },
+ },
+ required: ['tasklist'],
+ },
+ },
+];
+
+async function gFetch(pathAndQuery, init) {
+ if (!TOKEN) throw new Error('GOOGLE_ACCESS_TOKEN env var not set');
+ const res = await fetch(`${BASE}${pathAndQuery}`, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${TOKEN}`, Accept: 'application/json',
+ ...(init?.body ? { 'Content-Type': 'application/json' } : {}),
+ ...(init?.headers || {}),
+ },
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ let msg = text;
+ try { msg = JSON.parse(text).error?.message || text; } catch { /* keep raw */ }
+ throw new Error(`Tasks API ${res.status}: ${msg}`);
+ }
+ return text ? JSON.parse(text) : {};
+}
+
+async function callTool(name, args) {
+ if (name === 'list_tasklists') {
+ const r = await gFetch('/users/@me/lists');
+ return {
+ tasklists: (r.items || []).map((l) => ({ id: l.id, title: l.title, updated: l.updated })),
+ };
+ }
+ if (name === 'list_tasks') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ const max = Math.min(MAX_LIST, Math.max(1, parseInt(args.maxResults, 10) || 20));
+ const showCompleted = args.showCompleted === true;
+ const qs = new URLSearchParams({ maxResults: String(max), showCompleted: String(showCompleted) });
+ const r = await gFetch(`/lists/${tl}/tasks?${qs}`);
+ return {
+ tasks: (r.items || []).map((t) => ({
+ id: t.id,
+ title: t.title,
+ notes: t.notes,
+ status: t.status,
+ due: t.due,
+ completed: t.completed,
+ updated: t.updated,
+ parent: t.parent,
+ position: t.position,
+ })),
+ };
+ }
+ if (name === 'create_task') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ const title = String(args.title || '').trim();
+ if (!title) throw new Error('title is required');
+ const body = {
+ title,
+ ...(args.notes ? { notes: String(args.notes) } : {}),
+ ...(args.due ? { due: String(args.due) } : {}),
+ };
+ const r = await gFetch(`/lists/${tl}/tasks`, { method: 'POST', body: JSON.stringify(body) });
+ return { id: r.id, title: r.title, status: r.status, due: r.due };
+ }
+ if (name === 'update_task') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ const tid = encodeURIComponent(String(args.taskId || ''));
+ if (!tid) throw new Error('taskId is required');
+ const body = {};
+ if (typeof args.title === 'string') body.title = args.title;
+ if (typeof args.notes === 'string') body.notes = args.notes;
+ if (typeof args.due === 'string') body.due = args.due;
+ if (args.completed === true) body.status = 'completed';
+ else if (args.completed === false) body.status = 'needsAction';
+ // Google requires PATCH for partial updates (PUT would zero unspecified fields).
+ const r = await gFetch(`/lists/${tl}/tasks/${tid}`, { method: 'PATCH', body: JSON.stringify(body) });
+ return { id: r.id, title: r.title, status: r.status, due: r.due, completed: r.completed };
+ }
+ if (name === 'get_task') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ const tid = encodeURIComponent(String(args.taskId || ''));
+ if (!tid) throw new Error('taskId is required');
+ const r = await gFetch(`/lists/${tl}/tasks/${tid}`);
+ return r;
+ }
+ if (name === 'delete_task') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ const tid = encodeURIComponent(String(args.taskId || ''));
+ if (!tid) throw new Error('taskId is required');
+ await gFetch(`/lists/${tl}/tasks/${tid}`, { method: 'DELETE' });
+ return { ok: true };
+ }
+ if (name === 'move_task') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ const tid = encodeURIComponent(String(args.taskId || ''));
+ if (!tid) throw new Error('taskId is required');
+ const qs = new URLSearchParams();
+ if (args.parent) qs.set('parent', String(args.parent));
+ if (args.previous) qs.set('previous', String(args.previous));
+ const r = await gFetch(`/lists/${tl}/tasks/${tid}/move${qs.toString() ? `?${qs}` : ''}`, { method: 'POST' });
+ return { id: r.id, parent: r.parent, position: r.position };
+ }
+ if (name === 'clear_completed') {
+ const tl = encodeURIComponent(args.tasklist || '@default');
+ await gFetch(`/lists/${tl}/clear`, { method: 'POST' });
+ return { ok: true };
+ }
+ if (name === 'get_tasklist') {
+ const tl = encodeURIComponent(String(args.tasklist || ''));
+ if (!tl) throw new Error('tasklist is required');
+ const r = await gFetch(`/users/@me/lists/${tl}`);
+ return { id: r.id, title: r.title, updated: r.updated };
+ }
+ if (name === 'create_tasklist') {
+ const title = String(args.title || '').trim();
+ if (!title) throw new Error('title is required');
+ const r = await gFetch('/users/@me/lists', { method: 'POST', body: JSON.stringify({ title }) });
+ return { id: r.id, title: r.title, updated: r.updated };
+ }
+ if (name === 'update_tasklist') {
+ const tl = encodeURIComponent(String(args.tasklist || ''));
+ const title = String(args.title || '').trim();
+ if (!tl || !title) throw new Error('tasklist and title are both required');
+ const r = await gFetch(`/users/@me/lists/${tl}`, { method: 'PATCH', body: JSON.stringify({ title }) });
+ return { id: r.id, title: r.title, updated: r.updated };
+ }
+ if (name === 'delete_tasklist') {
+ const tl = encodeURIComponent(String(args.tasklist || ''));
+ if (!tl) throw new Error('tasklist is required');
+ await gFetch(`/users/@me/lists/${tl}`, { method: 'DELETE' });
+ return { ok: true };
+ }
+ throw new Error(`Unknown tool: ${name}`);
+}
+
+async function main() {
+ const server = new Server({ name: 'gtasks-rest', version: '0.1.0' }, { capabilities: { tools: {} } });
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ const { name, arguments: args = {} } = req.params;
+ try {
+ const result = await callTool(name, args || {});
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ return { content: [{ type: 'text', text: (err && err.message) || String(err) }], isError: true };
+ }
+ });
+ await server.connect(new StdioServerTransport());
+}
+
+main().catch((err) => {
+ process.stderr.write(`gtasks-mcp-server fatal: ${err && err.message || err}\n`);
+ process.exit(1);
+});
diff --git a/docs/plans/connectors-feishu-dingtalk-wecom.md b/docs/plans/connectors-feishu-dingtalk-wecom.md
new file mode 100644
index 00000000..94db1785
--- /dev/null
+++ b/docs/plans/connectors-feishu-dingtalk-wecom.md
@@ -0,0 +1,221 @@
+# 连接器扩展:飞书 / 钉钉 / 企业微信
+
+## Motivation
+
+对标 Google 五件套的国内场景。三家平台都没有官方 hosted MCP, 按 §6.5 既有
+stdio adapter pattern 自营: 每个 service 一个 `PC/bin/<svc>-mcp-server.cjs`,
+wrap vendor REST API; OAuth 走 Server 端 bridge (同 `google.py` 模式)。
+
+## 现状关键事实
+
+### 飞书 (Feishu)
+- 标准 OAuth 2.0 Authorization Code grant; `open.feishu.cn`; refresh_token
+ **会轮换** (同 GitHub / Notion) → 沿用 `manager._refreshGrantIfStale` 的
+ per-instance lock, 无新约束。
+- 三种 token (app / tenant / user) — 我们要 **user_access_token**, scope 在
+ 用户授权时挑选。
+- 海外版 Lark (`open.larksuite.com`) 接口形同 host 不同; **v1 只做国内
+ feishu.cn**, 海外 host 入 v2。
+- 候选 services (照 Google 模式按 service 拆 entry):
+ - **feishu_im** — `im:message`, `im:chat`: list_chats / get_chat /
+ list_messages / send_text_message
+ - **feishu_calendar** — `calendar:calendar`, `calendar:calendar.event`:
+ list_calendars / list_events / get_event / create_event
+ - **feishu_docs** — `docx:document`: get_document / create_document
+ - **feishu_sheets** — `sheets:spreadsheet`: list_sheets / read_range /
+ write_range
+ - **feishu_bitable** — `bitable:app`: list_apps / list_tables /
+ list_records / create_record / update_record (低代码用户量大, 主推)
+ - **feishu_task** — `task:task`: list_tasks / create_task / update_task
+
+### 钉钉 (DingTalk)
+- 标准 OAuth 2.0 Authorization Code grant (用户身份); `api.dingtalk.com`
+ (v2.0)。
+- API 1.0 vs 2.0 严重撕裂, **v1 完全用 2.0** (`x-acs-dingtalk-access-token`
+ header, 不是 Authorization Bearer)。adapter 里硬编码 header 名, 不走通用
+ Bearer helper。
+- 用户级 refresh_token 30d, access_token 2h, refresh 路径标准。
+- 候选 services:
+ - **dingtalk_todo** — `Todo.Read.Write`: list / create / update / complete
+ - **dingtalk_calendar** — `Calendar.Read.Write`: list / get / create
+ - 文档 / 钉盘 API 暴露面比飞书弱, v1 不做。
+
+### 企业微信 (WeCom) — 架构 blocker
+**关键问题**: 授权模型是 `corp ↔ app` (企业管理员把 App 装到本企业,
+员工在企微里授权这个 App), 不是 `user ↔ app`。三条路:
+
+1. **ISV 第三方应用** — 腾讯资质审核, 数月级 + 需企业主体, 暂无。
+2. **BYO 企业应用配置** — 用户自己当企业管理员, 创建自建应用,
+ 把 `corpid / agentid / corpsecret` 填给 Orkas。corpsecret 是长期密钥,
+ 不是 OAuth token, **强冲突 §6.5「no API-key / PAT entry」**。
+3. **只做扫码登录** — `snsapi_userinfo` 拿 `userid + corpid`, 后续无工具能力,
+ 不值得。
+
+**v1 建议**: catalog 加 `id: wecom` 占位 entry, 标
+`unavailable_reason: '需要 ISV 资质, 敬请期待'`, 不实现 OAuth + MCP。
+等 ISV 资质到位单独一波。**等用户确认这个处理**。
+
+## Components
+
+### 1. Catalog entries — `PC/src/main/features/connectors/catalog.ts`
+
+新增 6 (飞书) + 2 (钉钉) + 1 占位 (企微) = 9 个 entry。
+
+```ts
+{ id: 'feishu_im',
+ display_name: '飞书消息',
+ category: 'communication',
+ description_zh: '飞书 IM: 列群组 / 读消息 / 发消息',
+ description_en: 'Feishu IM: list chats / read messages / send text',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'feishu' },
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/feishu-im-mcp-server.cjs'],
+ oauth_env_key: 'FEISHU_ACCESS_TOKEN',
+ },
+ icon_svg: '<svg…/>' }
+// 其余飞书 5 个 + 钉钉 2 个同结构, 改 id / display_name / args / env_key
+{ id: 'wecom',
+ display_name: '企业微信',
+ category: 'communication',
+ description_zh: '企业微信 (需要 ISV 资质, 敬请期待)',
+ description_en: 'WeCom (requires ISV verification, coming soon)',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'wecom' },
+ unavailable_reason: '需要 ISV 资质, 敬请期待',
+ transport_template: null }
+```
+
+Icon SVG: 现状用 placeholder, 交付前由用户给最终 SVG 或我从 brand center
+抓。沿用既有 Google 套件的简化几何风格, 不引入彩色 brand SVG。
+
+### 2. Stdio MCP adapter scripts — `PC/bin/*.cjs`
+
+新增 8 个 (企微不建)。每个 ~200 行, 结构同 `gmail-mcp-server.cjs`: CJS +
+`@modelcontextprotocol/sdk/server/{index,stdio}` + StdioServerTransport,
+token 走 env, 每个 tool fetch 对应 REST endpoint。统一约束:
+
+- 长 list 默认 ≤50 条, 超长返回元数据 + `truncated: true`
+- 写工具默认 dry-run=false, 描述里强调有 side-effect
+- 错误码 → MCP tool error 解包 (复用 `gmailFetch` 同模式的小 helper)
+- 钉钉 adapter 用 `x-acs-dingtalk-access-token` header (其他都是
+ `Authorization: Bearer`)
+
+#### 飞书 — 各 service 起步集 (读多写少)
+
+| Service | Endpoint base | Tools |
+|---|---|---|
+| feishu_im | `/open-apis/im/v1` | list_chats, get_chat, list_messages, send_text_message |
+| feishu_calendar | `/open-apis/calendar/v4` | list_calendars, list_events, get_event, create_event |
+| feishu_docs | `/open-apis/docx/v1` | get_document (walk blocks → 合 textRun → plain text), create_document |
+| feishu_sheets | `/open-apis/sheets/{v2,v3}` | list_sheets, read_range, write_range |
+| feishu_bitable | `/open-apis/bitable/v1` | list_apps, list_tables, list_records, create_record, update_record |
+| feishu_task | `/open-apis/task/v2` | list_tasks, create_task, update_task |
+
+#### 钉钉
+
+| Service | Endpoint base | Tools |
+|---|---|---|
+| dingtalk_todo | `/v1.0/todo` | list_todos, create_todo, update_todo |
+| dingtalk_calendar | `/v1.0/calendar` | list_events, get_event, create_event |
+
+### 3. OAuth provider modules — Server 端
+
+新建 `Server/biz/connectors/oauth/{feishu,dingtalk,wecom}.py`, 实现
+`start / exchange / refresh`, scope 按 `_SCOPES_BY_CATALOG_ID[catalog_id]`
+选择, 照 `google.py` 既有模式。`wecom.py` v1 在 start 直接抛
+`E_PROVIDER_UNAVAILABLE` (catalog 也标 unavailable_reason, 双层防护)。
+
+环境变量:
+- `ORKAS_OAUTH_FEISHU_CLIENT_ID` / `..._SECRET` (即 app_id / app_secret)
+- `ORKAS_OAUTH_DINGTALK_CLIENT_ID` / `..._SECRET` (即 AppKey / AppSecret)
+- `ORKAS_OAUTH_WECOM_CLIENT_ID` / `..._SECRET` (v1 留位)
+
+### 4. apply-template.ts / manager.ts / oauth.ts / registry.ts
+
+**不动**。占位符解析 / per-instance refresh lock / 加密存储 /
+registry.update(patch) 都是通用层, 已经在 Google 套件验证过, 本批 100% 复用。
+
+### 5. UI
+
+- 渲染端 `connectors.js` 卡片网格自动收新 entry, **无新代码**。
+- i18n: category 标签 `category.communication` / `productivity` 已有, 无新
+ key。`unavailable_reason` 在 catalog 字段直接出 zh 文本 (保持现状), 不
+ i18n。
+
+### 6. 测试
+
+按 §9 "Don't write" 准则, **不为每个 adapter 写单元测试** (外部 API mock 价值低)。
+验收靠对话手测。
+
+`PC/test/main/features/connectors/apply-template.test.ts` 现有 placeholder
+fixture 覆盖通用解析, 不需改。
+
+## Change list
+
+**新增** (不算企微 adapter):
+- `PC/bin/feishu-{im,calendar,docs,sheets,bitable,task}-mcp-server.cjs` — 6
+- `PC/bin/dingtalk-{todo,calendar}-mcp-server.cjs` — 2
+- `Server/biz/connectors/oauth/feishu.py` — 新
+- `Server/biz/connectors/oauth/dingtalk.py` — 新
+- `Server/biz/connectors/oauth/wecom.py` — 占位 (start 抛 unavailable)
+
+**修改**:
+- `PC/src/main/features/connectors/catalog.ts` — +9 entries (含 wecom 占位)
+- `Server/biz/connectors/oauth/__init__.py` (或同等注册点) — 注册 3 个
+ provider
+
+**不动**:
+- `PC/src/main/features/connectors/{manager,apply-template,oauth,registry,mcp-client,oauth-config}.ts`
+- `PC/src/renderer/modules/connectors.js`
+
+## CLAUDE.md sync
+
+§6.5 当前规则已经覆盖 stdio adapter pattern / 视野 / refresh lock / 凭据
+存储, 本批是按既有规则执行, **无新约束**。
+
+Why: stdio adapter pattern 是为绕开 vendor-blocked MCP 设计的, 三家国内
+厂商都属同一类 (无 hosted MCP), pattern 直接复用, 不催生新规则。
+
+如果未来企微走 ISV 路线, 到时给 `§6.5` 加一段 "WeCom corp-bound OAuth"
+专项说明 (corpid / agentid 在 OAuth flow 中的位置)。
+
+## Open questions
+
+1. **企微 v1 处理**: 占位 + `unavailable_reason`, 还是冒着 §6.5 冲突走
+ BYO corpsecret? 我倾向占位。
+2. **飞书 / 钉钉 catalog 拆分粒度**: 6+2 个细粒度 entry vs 一个
+ `feishu_workspace` umbrella? 倾向拆分 (同 Google 模式), UI 可读性好且
+ 单 service 故障不影响别的。
+3. **Icon SVG**: 现在 placeholder, 交付前你给最终 SVG 还是我去 brand
+ center 抓?
+4. **飞书 IM `send_text_message`**: 算 high-impact side-effect, 是否默认从
+ `enabled_subtools` 排除, 用户在连接器面板里手动启用? (同样问题: 飞书
+ calendar `create_event`, bitable `create_record/update_record`, 钉钉
+ `create_todo/update_todo` 等)
+
+## 验收
+
+每个 service 在对话里跑通一条最简 read tool:
+
+- feishu_im: "列出我的飞书群" → `list_chats`
+- feishu_calendar: "今天的飞书会议" → `list_events`
+- feishu_docs: "读飞书文档 :id" → `get_document`
+- feishu_sheets: "读 :token 的 A1:C10" → `read_range`
+- feishu_bitable: "列 :app 的 :table 前 10 条" → `list_records`
+- feishu_task: "列我的飞书任务" → `list_tasks`
+- dingtalk_todo: "列我的钉钉待办" → `list_todos`
+- dingtalk_calendar: "今天的钉钉日程" → `list_events`
+
+加一条 write 路径 sanity (任选一个 service 跑通 `send` / `create`)。
+
+通过后删本计划文件。
+
+## 工作量预估
+
+- 8 adapter × ~200 行 ≈ 1600 行 CJS, ~6h
+- 3 Python provider 模块 ~200 行 × 3 ≈ 600 行, ~2h
+- catalog + scope 表 ~100 行, ~30min
+- 总计 ~1.5 个工作日 (不含飞书 / 钉钉 OAuth 应用申请 + 审核等待)
diff --git a/src/core-agent/test/skills.test.ts b/src/core-agent/test/skills.test.ts
index a79d73bf..704ff49f 100644
--- a/src/core-agent/test/skills.test.ts
+++ b/src/core-agent/test/skills.test.ts
@@ -162,16 +162,18 @@ describe("SkillLoader", () => {
expect(block).not.toMatch(/\(`/);
});
- it("parseSpec rewrites frontmatter name to match dir (invariant enforcement)", () => {
- // Hand-edited SKILL.md with drifting `name` shouldn't break anything —
- // the loader normalizes to the directory name and logs a warning.
+ it("parseSpec keeps frontmatter name distinct from dir id (id≠name invariant)", () => {
+ // The loader decouples id (= dir basename, used as `read_file` path
+ // component) from name (= frontmatter name, the LLM-facing display
+ // label). Marketplace installs deliberately let these diverge (dir is
+ // the 12-hex server_id, name is the authored human label).
const customDir = path.join(root, "custom");
writeSkill(customDir, "web-summary", { name: "WebSummaryLegacy", description: "x" });
const loader = new SkillLoader({ dirs: [customDir] });
const [spec] = loader.list();
expect(spec.id).toBe("web-summary");
- expect(spec.name).toBe("web-summary"); // not "WebSummaryLegacy"
+ expect(spec.name).toBe("WebSummaryLegacy"); // frontmatter is preserved verbatim
});
});
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index 6556b816..aa2d2a7b 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -544,7 +544,18 @@ export function isCliAgent(agent: Pick<Agent, 'runtime'> | null | undefined): bo
interface AgentListCache { stamp: string; data: Agent[] }
let _agentListCache: AgentListCache | null = null;
-function _invalidateAgentListCache(): void { _agentListCache = null; }
+function _invalidateAgentListCache(): void {
+ _agentListCache = null;
+ // Notify the sync engine (lazy-require — stripped in OrkasOpen builds). Every cache-invalidate
+ // is also a disk-mutation point, so co-locating the dirty signal here covers all the
+ // existing call sites without sprinkling sync calls across the file. The relPath here is
+ // informational only — the engine ignores it and walks `cloud/` itself.
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const sync = require('./sync') as { markDirty?: (domain: string, relPath: string) => void };
+ sync.markDirty?.('agents', 'cloud/agents');
+ } catch { /* features/sync stripped */ }
+}
/** Public re-export of `_invalidateAgentListCache` for cross-module callers (sync engine).
* **Why exposed**: `listAgents` caches the disk spec list keyed on the two source dirs'
@@ -1100,7 +1111,7 @@ export async function deleteCustomAgent(agentId: string): Promise<boolean> {
catch (err) { log.warn(`rm failed user=${uid} agent=${agentId}: ${(err as Error).message}`); }
invalidateLineCount(path.join(chatDir, 'chat.jsonl'));
}
- const sessionId = defaultAgentEditSessionId(uid, agentId);
+ const sessionId = defaultAgentEditSessionId(agentId);
try { evictSession(sessionId); } catch { /* cache may not hold it */ }
const sessionJsonl = userSessionFile(uid, sessionId);
try { await fsp.unlink(sessionJsonl); }
@@ -1286,8 +1297,8 @@ function agentChatMetaPath(userId: string, agentId: string): string {
return path.join(agentChatDir(userId, agentId), 'chat.json');
}
-function defaultAgentEditSessionId(userId: string, agentId: string): string {
- return `${userId}-agent-${agentId}`;
+function defaultAgentEditSessionId(agentId: string): string {
+ return `agent-${agentId}`;
}
async function loadAgentChatMeta(userId: string, agentId: string): Promise<AgentChatMeta> {
@@ -1326,7 +1337,7 @@ export async function clearAgentChat(userId: string, agentId: string): Promise<b
// the LLM retains its full prior context even though the UI history is
// empty — same bug pattern as clearSkillChat (paths from before a
// promote-to-builtin survive in the LLM's memory).
- const sessionId = defaultAgentEditSessionId(userId, agentId);
+ const sessionId = defaultAgentEditSessionId(agentId);
try { evictSession(sessionId); } catch { /* not in cache */ }
try { await fsp.unlink(userSessionFile(userId, sessionId)); }
catch (err) {
@@ -1405,7 +1416,7 @@ export async function sendToAgentEditChat(userId: string, agentId: string, conte
if (agent.source !== 'custom') return { ok: false, error: t('errors.builtin_agent_not_editable') };
const meta = await loadAgentChatMeta(userId, agentId);
- const sessionId = meta.session_id || defaultAgentEditSessionId(userId, agentId);
+ const sessionId = meta.session_id || defaultAgentEditSessionId(agentId);
const systemPrompt = buildAgentEditSystemPrompt(agent);
@@ -1465,7 +1476,7 @@ export async function* streamSendToAgentEditChat(
}
const meta = await loadAgentChatMeta(userId, agentId);
- const sessionId = meta.session_id || defaultAgentEditSessionId(userId, agentId);
+ const sessionId = meta.session_id || defaultAgentEditSessionId(agentId);
const systemPrompt = buildAgentEditSystemPrompt(agent);
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 957e04ba..66b94d50 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -203,7 +203,7 @@ export async function createConversation(userId: string, {
kind,
agent_id: agentId || '',
skill_id: skillId || '',
- session_id: buildGconvSessionId(userId, cid),
+ session_id: buildGconvSessionId(cid),
...(projectId ? { project_id: projectId } : {}),
created_at: nowIso(),
updated_at: nowIso(),
@@ -254,14 +254,14 @@ export async function deleteConversation(userId: string, cid: string): Promise<b
search.dropChatConversation(userId, cid);
// Purge commander session + every per-agent member session.
- purgeSession(userId, removed?.session_id || buildGconvSessionId(userId, cid));
+ purgeSession(userId, removed?.session_id || buildGconvSessionId(cid));
// gmember sessions: glob the sessions dir for `<uid>-gmember-<cid>-*` —
// we can't rely on readMembers() because `groupChat.dropConv` above has
// already removed members.json (the historical cause of the 50+ orphan
// gmember files we found on the dev box: readMembers returns {actors:[]}
// → the for-loop never ran → every per-agent worker session leaked).
// Scanning the actual filesystem is the truth source.
- const gmemberPrefix = `${userId}-gmember-${cid}-`;
+ const gmemberPrefix = `gmember-${cid}-`;
try {
const names = await fsp.readdir(userSessionsDir(userId));
for (const n of names) {
diff --git a/src/main/features/component_enabled.ts b/src/main/features/component_enabled.ts
index dd2962b9..1d84c02a 100644
--- a/src/main/features/component_enabled.ts
+++ b/src/main/features/component_enabled.ts
@@ -43,19 +43,37 @@ import { createLogger } from '../logger';
const log = createLogger('component-enabled');
+// Lazy require sync: the module is stripped from OrkasOpen builds, and a static import would
+// break that build at module-load time. When sync is absent we silently no-op — the file
+// still sits at `cloud/config/` for whenever sync becomes available.
+function _notifyDirty(): void {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const sync = require('./sync') as { markDirty?: (domain: string, relPath: string) => void };
+ sync.markDirty?.('component_enabled', 'cloud/config/component-enabled.json');
+ } catch { /* features/sync stripped */ }
+}
+
const SCHEMA_VERSION = 1;
export interface ComponentEnabledFile {
version: number;
agents: Record<string, boolean>;
skills: Record<string, boolean>;
+ /** Per-user soft-disable for connector instances. Independent of OAuth grant / MCP connection
+ * state — a "disabled" connector keeps its tokens and stays connected, but is invisible to
+ * the LLM (`resolveVisibleConnectors` filters it out). "Disconnect" (manager.removeInstance)
+ * is the heavier action that wipes the grant. */
+ connectors: Record<string, boolean>;
}
function emptyFile(): ComponentEnabledFile {
- return { version: SCHEMA_VERSION, agents: {}, skills: {} };
+ return { version: SCHEMA_VERSION, agents: {}, skills: {}, connectors: {} };
}
-/** Read the per-user enabled-overrides file. Missing / corrupt → empty defaults. */
+/** Read the per-user enabled-overrides file. Missing / corrupt → empty defaults.
+ * Old v1 files without a `connectors` field are auto-padded with `{}` (no migration needed —
+ * missing key = treat-as-enabled is the contract). */
export function readEnabledMap(uid: string): ComponentEnabledFile {
const p = userComponentEnabledFile(uid);
try {
@@ -67,6 +85,7 @@ export function readEnabledMap(uid: string): ComponentEnabledFile {
version: SCHEMA_VERSION,
agents: (parsed.agents && typeof parsed.agents === 'object') ? sanitiseMap(parsed.agents) : {},
skills: (parsed.skills && typeof parsed.skills === 'object') ? sanitiseMap(parsed.skills) : {},
+ connectors: (parsed.connectors && typeof parsed.connectors === 'object') ? sanitiseMap(parsed.connectors) : {},
};
} catch (err) {
log.warn(`read failed, using empty defaults: ${(err as Error).message}`);
@@ -107,6 +126,12 @@ export function isSkillEnabled(uid: string, skillId: string, specDefault?: boole
return resolve(map.skills, skillId, specDefault);
}
+export function isConnectorEnabled(uid: string, connectorId: string, specDefault?: boolean): boolean {
+ if (!connectorId) return true;
+ const map = readEnabledMap(uid);
+ return resolve(map.connectors, connectorId, specDefault);
+}
+
function resolve(overrides: Record<string, boolean>, id: string, specDefault?: boolean): boolean {
const o = overrides[id];
if (typeof o === 'boolean') return o;
@@ -121,10 +146,12 @@ export function setAgentEnabled(uid: string, agentId: string, enabled: boolean):
version: SCHEMA_VERSION,
agents: { ...cur.agents },
skills: { ...cur.skills },
+ connectors: { ...cur.connectors },
};
if (enabled) delete next.agents[agentId];
else next.agents[agentId] = false;
writeAtomic(uid, next);
+ _notifyDirty();
log.info(`agent ${agentId} → ${enabled ? 'enabled' : 'disabled'}`);
}
@@ -135,19 +162,38 @@ export function setSkillEnabled(uid: string, skillId: string, enabled: boolean):
version: SCHEMA_VERSION,
agents: { ...cur.agents },
skills: { ...cur.skills },
+ connectors: { ...cur.connectors },
};
if (enabled) delete next.skills[skillId];
else next.skills[skillId] = false;
writeAtomic(uid, next);
+ _notifyDirty();
log.info(`skill ${skillId} → ${enabled ? 'enabled' : 'disabled'}`);
}
+export function setConnectorEnabled(uid: string, connectorId: string, enabled: boolean): void {
+ if (!connectorId) throw new Error('connectorId required');
+ const cur = readEnabledMap(uid);
+ const next: ComponentEnabledFile = {
+ version: SCHEMA_VERSION,
+ agents: { ...cur.agents },
+ skills: { ...cur.skills },
+ connectors: { ...cur.connectors },
+ };
+ if (enabled) delete next.connectors[connectorId];
+ else next.connectors[connectorId] = false;
+ writeAtomic(uid, next);
+ _notifyDirty();
+ log.info(`connector ${connectorId} → ${enabled ? 'enabled' : 'disabled'}`);
+}
+
/** Bulk read — used by the renderer to render toggle states without re-fetching
- * per row. Returns `{agents: Set<disabledId>, skills: Set<disabledId>}`. */
-export function readDisabledSets(uid: string): { agents: Set<string>; skills: Set<string> } {
+ * per row. Returns `{agents, skills, connectors: Set<disabledId>}`. */
+export function readDisabledSets(uid: string): { agents: Set<string>; skills: Set<string>; connectors: Set<string> } {
const map = readEnabledMap(uid);
return {
agents: new Set(Object.keys(map.agents)),
skills: new Set(Object.keys(map.skills)),
+ connectors: new Set(Object.keys(map.connectors)),
};
}
diff --git a/src/main/features/connectors/apply-template.ts b/src/main/features/connectors/apply-template.ts
index c4dcc80e..2f92755b 100644
--- a/src/main/features/connectors/apply-template.ts
+++ b/src/main/features/connectors/apply-template.ts
@@ -8,10 +8,49 @@
* Validation lives here because catalog entries don't know whether a token is still valid;
* throw on missing pieces, the caller surfaces the error.
*/
+import { app } from 'electron';
+
+import * as paths from '../../paths';
import type { CatalogEntry, OAuthGrant, Transport } from './types';
type EnvSynth = (access_token: string) => Record<string, string>;
+// Cache the Electron-as-Node values once per process — `process.execPath` and PC_ROOT are
+// immutable at runtime. Lazy because `app` is undefined in vitest paths that pull this module
+// without an Electron context.
+let _electronAsNode: { node: string; pcDir: string } | null = null;
+function _electronAsNodeVars(): { node: string; pcDir: string } {
+ if (_electronAsNode) return _electronAsNode;
+ const isPackaged = !!app && app.isPackaged;
+ // Packaged builds: rewrite `app.asar` → `app.asar.unpacked` so the spawned child can read the
+ // adapter script as a real file on disk (asar contents aren't visible to a child process that
+ // doesn't have the asar mount logic). Mirrors `client.ts::buildSkillSandboxEnv`.
+ const pcDir = isPackaged
+ ? paths.PC_ROOT.replace(/\bapp\.asar\b/, 'app.asar.unpacked')
+ : paths.PC_ROOT;
+ _electronAsNode = { node: process.execPath, pcDir };
+ return _electronAsNode;
+}
+
+/** Resolve `${ORKAS_NODE}` / `${ORKAS_PC_DIR}` placeholders inside a stdio template's
+ * command / args. Lets connector catalog entries reference our adapter scripts by symbolic
+ * path without hard-coding absolute paths at catalog-author time. Unknown placeholders throw
+ * to surface typos at install — silent passthrough would let `${ORKS_NODE}` slip through and
+ * spawn a literal-named binary that doesn't exist. */
+function _resolvePlaceholders(s: string): string {
+ const vars = _electronAsNodeVars();
+ return s.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/g, (_m, key) => {
+ if (key === 'ORKAS_NODE') return vars.node;
+ if (key === 'ORKAS_PC_DIR') return vars.pcDir;
+ throw new Error(`unknown placeholder \${${key}} in transport template`);
+ });
+}
+
+function _hasElectronAsNodePlaceholder(tpl: { command: string; args: string[] }): boolean {
+ if (/\$\{ORKAS_NODE\}/.test(tpl.command)) return true;
+ return tpl.args.some((a) => /\$\{ORKAS_NODE\}/.test(a) || /\$\{ORKAS_PC_DIR\}/.test(a));
+}
+
const _SYNTHESIZERS: Record<string, EnvSynth> = {
// Notion OAuth: the official @notionhq/notion-mcp-server reads `OPENAPI_MCP_HEADERS`, a JSON
// blob holding the Authorization + Notion-Version headers.
@@ -44,10 +83,20 @@ export function applyTemplate(entry: CatalogEntry, grant: OAuthGrant): Transport
} else {
throw new Error('OAuth stdio template needs either oauth_env_key or env_synthesizer');
}
+ // Electron-as-Node injection: templates pointing at our own bundled adapter scripts (e.g.
+ // `${ORKAS_NODE}` + `${ORKAS_PC_DIR}/bin/gmail-mcp-server.cjs`) need `ELECTRON_RUN_AS_NODE=1`
+ // in the child env so Electron boots as plain Node. Same pattern as `client.ts::
+ // buildSkillSandboxEnv`. We only inject these when the template actually uses a
+ // placeholder — third-party stdio servers like the legacy `npx @modelcontextprotocol/server-X`
+ // pattern stay env-clean.
+ if (_hasElectronAsNodePlaceholder(tpl)) {
+ const vars = _electronAsNodeVars();
+ env = { ...env, ELECTRON_RUN_AS_NODE: '1', ORKAS_NODE: vars.node, ORKAS_PC_DIR: vars.pcDir };
+ }
return {
kind: 'stdio',
- command: tpl.command,
- args: [...tpl.args],
+ command: _resolvePlaceholders(tpl.command),
+ args: tpl.args.map((a) => _resolvePlaceholders(a)),
env,
};
}
diff --git a/src/main/features/connectors/catalog-google.ts b/src/main/features/connectors/catalog-google.ts
new file mode 100644
index 00000000..afb1a6b7
--- /dev/null
+++ b/src/main/features/connectors/catalog-google.ts
@@ -0,0 +1,121 @@
+/**
+ * Google Workspace catalog entries — extracted from `catalog.ts` so they can be stripped
+ * from the OrkasOpen build (Google requires Workspace Developer Preview Program enrollment
+ * + production CASA verification, which the OSS distribution can't satisfy). PC builds
+ * include this file via a try/require in `catalog.ts`; OrkasOpen ships without it (see
+ * `OpenSource/SyncCode/strip-rules.json` `forbidden_files`).
+ *
+ * Includes:
+ * - `google-workspace` (UI-only bundle; `bundle_member_ids` fans out OAuth to all 5)
+ * - `gmail`, `gcal`, `gdocs`, `gsheets`, `gtasks` (the 5 member entries, each backed by a
+ * local stdio adapter under `PC/bin/`)
+ *
+ * Adding a new Google service: drop a new entry here + `bin/<svc>-mcp-server.cjs` adapter +
+ * Server's `_SCOPES_BY_CATALOG_ID` row, and union the scope into `google-workspace`'s
+ * member list if you want it covered by the bundle's single consent.
+ */
+import type { CatalogEntry } from './types';
+
+export const GOOGLE_ENTRIES: CatalogEntry[] = [
+ // ── Google Workspace ────────────────────────────────────────────────────
+ // One UI bundle (`google-workspace`) groups the 5 service entries below — a single OAuth
+ // flow with `union(scopes)` provisions all 5 instances. Each member entry keeps its own
+ // stdio adapter / tool surface so the model still sees 5 independent connectors with
+ // service-specific tool names. Bypasses Google's MCP wrapper service
+ // (`gmailmcp.googleapis.com`) which is in Developer Preview with a project-level allowlist
+ // that third-party OAuth clients can't reach. See `bin/gmail-mcp-server.cjs` header for
+ // rationale and PC/CLAUDE.md §6.5.
+ {
+ id: 'google-workspace',
+ display_name: 'Google Workspace',
+ icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285f4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34a853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#fbbc05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#ea4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>',
+ category: 'productivity',
+ description_zh: 'Gmail / Google 日历 / Google 文档 / Google 表格 / Google 任务 — 一次授权,5 项服务一起接入。',
+ description_en: 'Gmail / Google Calendar / Google Docs / Google Sheets / Google Tasks — one consent, all 5 services connected.',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'google' },
+ // Bundle: no transport of its own; OAuth fans out to the 5 member instances below.
+ transport_template: null,
+ bundle_member_ids: ['gmail', 'gcal', 'gdocs', 'gsheets', 'gtasks'],
+ },
+ {
+ id: 'gmail',
+ display_name: 'Gmail',
+ icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285f4" d="M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z"/><path fill="#34a853" d="M5.455 21.003V11.73l-3.819-2.864v10.5c0 .904.732 1.637 1.636 1.637z"/><path fill="#ea4335" d="M18.545 21.003V11.73l3.819-2.864v10.5a1.636 1.636 0 0 1-1.636 1.637z"/><path fill="#fbbc04" d="M5.455 11.73 12 16.64l6.545-4.91V4.64L12 9.548 5.455 4.64z"/><path fill="#c5221f" d="M0 5.457v3.41l5.455 4.092V4.64L3.927 3.494C2.309 2.28 0 3.434 0 5.457z"/></svg>',
+ category: 'communication',
+ description_zh: '读 / 发邮件、管理标签、自动化收件箱。',
+ description_en: 'Read and send mail, manage labels, automate the inbox.',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'google' },
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/gmail-mcp-server.cjs'],
+ oauth_env_key: 'GOOGLE_ACCESS_TOKEN',
+ },
+ },
+ {
+ id: 'gcal',
+ display_name: 'Google Calendar',
+ icon_svg: '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M152.6 47.4H47.4v105.2h105.2z"/><path fill="#1a73e8" d="M152.6 200 200 152.6l-23.7-4.2-23.7 4.2-4.6 21.6z"/><path fill="#ea4335" d="M0 152.6v32.6c0 8.4 6.8 15.3 15.3 15.3h32.6l4.9-23.7-4.9-23.7-25-4.9z"/><path fill="#188038" d="M200 47.4V14.7c0-8.4-6.8-15.3-15.3-15.3h-32.6q-4.45 22.05-4.9 24.6.45 2.65 4.9 23.4 25 4.45 23.7 0z"/><path fill="#fbbc04" d="M200 47.4h-47.4v105.2H200z"/><path fill="#34a853" d="M152.6 152.6H47.4V200h105.2z"/><path fill="#4285f4" d="M152.6 0H15.3C6.8 0 0 6.8 0 15.3v137.3h47.4V47.4h105.2z"/><path fill="#4285f4" d="m69 130.5c-3.9-2.7-6.7-6.5-8.2-11.6l9.1-3.8c.8 3.2 2.4 5.7 4.5 7.5 2.1 1.8 4.7 2.7 7.7 2.7s5.7-.9 7.8-2.8 3.2-4.2 3.2-7-1.1-5.3-3.4-7.2-5.1-2.8-8.5-2.8h-5.3v-9h4.7c2.9 0 5.4-.8 7.5-2.4 2-1.6 3.1-3.8 3.1-6.5 0-2.5-.9-4.4-2.6-5.9s-3.9-2.2-6.5-2.2-4.6.7-6 2-2.5 3-3.1 4.9l-9-3.7c1.1-3.1 3.1-5.9 6.1-8.3 3-2.4 6.8-3.6 11.4-3.6 3.4 0 6.5.7 9.2 2 2.7 1.3 4.9 3.2 6.4 5.5 1.6 2.4 2.3 5 2.3 8 0 3-.7 5.5-2.2 7.6s-3.3 3.7-5.4 4.8v.5q4.05 1.65 6.6 5.1c2.55 3.45 2.6 5.1 2.6 8.5s-.8 6.2-2.5 8.8c-1.7 2.6-3.9 4.6-6.8 6.1q-4.35 2.25-9.6 2.25c-4.05 0-7.7-.9-10.8-2.6zm47.7-37.8-10 7.3-5-7.6 18-13h6.9v61.3h-10z"/></svg>',
+ category: 'productivity',
+ description_zh: '查看、创建、修改日历事件与会议。',
+ description_en: 'View, create, and update calendar events and meetings.',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'google' },
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/gcal-mcp-server.cjs'],
+ oauth_env_key: 'GOOGLE_ACCESS_TOKEN',
+ },
+ },
+ {
+ id: 'gdocs',
+ display_name: 'Google Docs',
+ icon_svg: '<svg viewBox="0 0 47 65" xmlns="http://www.w3.org/2000/svg"><path fill="#4285F4" d="M29.375 0H4.4063C1.9688 0 0 1.96875 0 4.40625V60.5938C0 63.0313 1.9688 65 4.4063 65H42.5938C45.0313 65 47 63.0313 47 60.5938V17.625L36.7188 10.2813z"/><path fill="#1967D2" d="m30.6406 16.3906 16.3594 16.3594v-15.125z"/><path fill="#fff" d="M11.75 47.0625H35.25V44.125H11.75zm0-5.875H35.25V38.25H11.75zm0-11.75v2.9375H35.25V29.4375zm0 8.8125H35.25V32.375H11.75z"/><path fill="#FFF" d="M29.375 0v13.2188c0 2.4375 1.9687 4.4062 4.4062 4.4062H47z"/></svg>',
+ category: 'productivity',
+ description_zh: '读 / 写 Google Docs 文档,自动化文档工作流。',
+ description_en: 'Read, create, and manage Google Docs from your workflows.',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'google' },
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/gdocs-mcp-server.cjs'],
+ oauth_env_key: 'GOOGLE_ACCESS_TOKEN',
+ },
+ },
+ {
+ id: 'gsheets',
+ display_name: 'Google Sheets',
+ icon_svg: '<svg viewBox="0 0 47 65" xmlns="http://www.w3.org/2000/svg"><path fill="#0F9D58" d="M29.375 0H4.4063C1.9688 0 0 1.96875 0 4.40625V60.5938C0 63.0313 1.9688 65 4.4063 65H42.5938C45.0313 65 47 63.0313 47 60.5938V17.625L36.7188 10.2813z"/><path fill="#0B8043" d="m30.6406 16.3906 16.3594 16.3594v-15.125z"/><path fill="#fff" d="M35.25 29.4375h-23.5v17.625H35.25zm-13.2188 14.875h-8.0937v-4.2188h8.0937zm0-6.4063h-8.0937v-4.2187h8.0937zm10.5625 6.4063h-8.0937v-4.2188h8.0937zm0-6.4063h-8.0937v-4.2187h8.0937z"/><path fill="#FFF" d="M29.375 0v13.2188c0 2.4375 1.9687 4.4062 4.4062 4.4062H47z"/></svg>',
+ category: 'data',
+ description_zh: '把电子表格当作数据源,读写单元格与公式。',
+ description_en: 'Use spreadsheets as a data source — read and write cells and formulas.',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'google' },
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/gsheets-mcp-server.cjs'],
+ oauth_env_key: 'GOOGLE_ACCESS_TOKEN',
+ },
+ },
+ {
+ id: 'gtasks',
+ display_name: 'Google Tasks',
+ icon_svg: '<svg viewBox="0 0 192 192" xmlns="http://www.w3.org/2000/svg"><path fill="#FBBC04" d="m139.8 60.6 19.5 19.5 32.7-32.6L172.5 28z"/><path fill="#34A853" d="M88.5 111.9 67 90.5l-19.6 19.6 41 41 84.1-84-19.5-19.6z"/><path fill="#1A73E8" d="M97 192c52.7 0 95.5-42.8 95.5-95.6 0-2.5-.2-5-.4-7.5-2 2.4-83 83-83 83l-41.7-41.7-67 67c17.3 17 41 27.8 67 27.8z"/><path fill="#188038" d="M30 162c-37.6-37.6-37.6-98.6 0-136.2s98.6-37.6 136.2 0z"/></svg>',
+ category: 'productivity',
+ description_zh: '把任务管理直接接入工作流。',
+ description_en: 'Integrate task management directly into your workflows.',
+ auth_mode: 'server_bridge',
+ oauth: { provider_id: 'google' },
+ transport_template: {
+ kind: 'stdio',
+ command: '${ORKAS_NODE}',
+ args: ['${ORKAS_PC_DIR}/bin/gtasks-mcp-server.cjs'],
+ oauth_env_key: 'GOOGLE_ACCESS_TOKEN',
+ },
+ },
+];
diff --git a/src/main/features/connectors/catalog.ts b/src/main/features/connectors/catalog.ts
index cd80534a..d59c335a 100644
--- a/src/main/features/connectors/catalog.ts
+++ b/src/main/features/connectors/catalog.ts
@@ -73,89 +73,27 @@ export const CONNECTOR_CATALOG: CatalogEntry[] = [
oauth_header_key: 'Authorization',
},
},
- // ── Google Workspace ────────────────────────────────────────────────────
- // Five separate entries (Gmail / Calendar / Docs / Sheets / Tasks) share **one** Google OAuth
- // client (registered once in GCP console with all 5 scopes + identity scopes). Per-entry
- // scope subset is picked by `Server/biz/connectors/oauth/google.py::build_authorize_url(state,
- // catalog_id)` reading the entry's `id`. Each entry runs its own service-specific remote MCP
- // server, so a user who only installs Gmail doesn't see Sheets tools in the runner's tool list.
- {
- id: 'gmail',
- display_name: 'Gmail',
- icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#4285f4" d="M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z"/><path fill="#34a853" d="M5.455 21.003V11.73l-3.819-2.864v10.5c0 .904.732 1.637 1.636 1.637z"/><path fill="#ea4335" d="M18.545 21.003V11.73l3.819-2.864v10.5a1.636 1.636 0 0 1-1.636 1.637z"/><path fill="#fbbc04" d="M5.455 11.73 12 16.64l6.545-4.91V4.64L12 9.548 5.455 4.64z"/><path fill="#c5221f" d="M0 5.457v3.41l5.455 4.092V4.64L3.927 3.494C2.309 2.28 0 3.434 0 5.457z"/></svg>',
- category: 'communication',
- description_zh: '读 / 发邮件、管理标签、自动化收件箱。',
- description_en: 'Read and send mail, manage labels, automate the inbox.',
- auth_mode: 'server_bridge',
- oauth: { provider_id: 'google' },
- transport_template: {
- kind: 'streamable-http',
- url: 'https://gmailmcp.googleapis.com/mcp/v1',
- oauth_header_key: 'Authorization',
- },
- },
- {
- id: 'gcal',
- display_name: 'Google Calendar',
- icon_svg: '<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M152.6 47.4H47.4v105.2h105.2z"/><path fill="#1a73e8" d="M152.6 200 200 152.6l-23.7-4.2-23.7 4.2-4.6 21.6z"/><path fill="#ea4335" d="M0 152.6v32.6c0 8.4 6.8 15.3 15.3 15.3h32.6l4.9-23.7-4.9-23.7-25-4.9z"/><path fill="#188038" d="M200 47.4V14.7c0-8.4-6.8-15.3-15.3-15.3h-32.6q-4.45 22.05-4.9 24.6.45 2.65 4.9 23.4 25 4.45 23.7 0z"/><path fill="#fbbc04" d="M200 47.4h-47.4v105.2H200z"/><path fill="#34a853" d="M152.6 152.6H47.4V200h105.2z"/><path fill="#4285f4" d="M152.6 0H15.3C6.8 0 0 6.8 0 15.3v137.3h47.4V47.4h105.2z"/><path fill="#4285f4" d="m69 130.5c-3.9-2.7-6.7-6.5-8.2-11.6l9.1-3.8c.8 3.2 2.4 5.7 4.5 7.5 2.1 1.8 4.7 2.7 7.7 2.7s5.7-.9 7.8-2.8 3.2-4.2 3.2-7-1.1-5.3-3.4-7.2-5.1-2.8-8.5-2.8h-5.3v-9h4.7c2.9 0 5.4-.8 7.5-2.4 2-1.6 3.1-3.8 3.1-6.5 0-2.5-.9-4.4-2.6-5.9s-3.9-2.2-6.5-2.2-4.6.7-6 2-2.5 3-3.1 4.9l-9-3.7c1.1-3.1 3.1-5.9 6.1-8.3 3-2.4 6.8-3.6 11.4-3.6 3.4 0 6.5.7 9.2 2 2.7 1.3 4.9 3.2 6.4 5.5 1.6 2.4 2.3 5 2.3 8 0 3-.7 5.5-2.2 7.6s-3.3 3.7-5.4 4.8v.5q4.05 1.65 6.6 5.1c2.55 3.45 2.6 5.1 2.6 8.5s-.8 6.2-2.5 8.8c-1.7 2.6-3.9 4.6-6.8 6.1q-4.35 2.25-9.6 2.25c-4.05 0-7.7-.9-10.8-2.6zm47.7-37.8-10 7.3-5-7.6 18-13h6.9v61.3h-10z"/></svg>',
- category: 'productivity',
- description_zh: '查看、创建、修改日历事件与会议。',
- description_en: 'View, create, and update calendar events and meetings.',
- auth_mode: 'server_bridge',
- oauth: { provider_id: 'google' },
- transport_template: {
- kind: 'streamable-http',
- url: 'https://calendarmcp.googleapis.com/mcp/v1',
- oauth_header_key: 'Authorization',
- },
- },
- {
- id: 'gdocs',
- display_name: 'Google Docs',
- icon_svg: '<svg viewBox="0 0 47 65" xmlns="http://www.w3.org/2000/svg"><path fill="#4285F4" d="M29.375 0H4.4063C1.9688 0 0 1.96875 0 4.40625V60.5938C0 63.0313 1.9688 65 4.4063 65H42.5938C45.0313 65 47 63.0313 47 60.5938V17.625L36.7188 10.2813z"/><path fill="#1967D2" d="m30.6406 16.3906 16.3594 16.3594v-15.125z"/><path fill="#fff" d="M11.75 47.0625H35.25V44.125H11.75zm0-5.875H35.25V38.25H11.75zm0-11.75v2.9375H35.25V29.4375zm0 8.8125H35.25V32.375H11.75z"/><path fill="#FFF" d="M29.375 0v13.2188c0 2.4375 1.9687 4.4062 4.4062 4.4062H47z"/></svg>',
- category: 'productivity',
- description_zh: '读 / 写 Google Docs 文档,自动化文档工作流。',
- description_en: 'Read, create, and manage Google Docs from your workflows.',
- auth_mode: 'server_bridge',
- oauth: { provider_id: 'google' },
- transport_template: {
- kind: 'streamable-http',
- url: 'https://docsmcp.googleapis.com/mcp/v1',
- oauth_header_key: 'Authorization',
- },
- },
- {
- id: 'gsheets',
- display_name: 'Google Sheets',
- icon_svg: '<svg viewBox="0 0 47 65" xmlns="http://www.w3.org/2000/svg"><path fill="#0F9D58" d="M29.375 0H4.4063C1.9688 0 0 1.96875 0 4.40625V60.5938C0 63.0313 1.9688 65 4.4063 65H42.5938C45.0313 65 47 63.0313 47 60.5938V17.625L36.7188 10.2813z"/><path fill="#0B8043" d="m30.6406 16.3906 16.3594 16.3594v-15.125z"/><path fill="#fff" d="M35.25 29.4375h-23.5v17.625H35.25zm-13.2188 14.875h-8.0937v-4.2188h8.0937zm0-6.4063h-8.0937v-4.2187h8.0937zm10.5625 6.4063h-8.0937v-4.2188h8.0937zm0-6.4063h-8.0937v-4.2187h8.0937z"/><path fill="#FFF" d="M29.375 0v13.2188c0 2.4375 1.9687 4.4062 4.4062 4.4062H47z"/></svg>',
- category: 'data',
- description_zh: '把电子表格当作数据源,读写单元格与公式。',
- description_en: 'Use spreadsheets as a data source — read and write cells and formulas.',
- auth_mode: 'server_bridge',
- oauth: { provider_id: 'google' },
- transport_template: {
- kind: 'streamable-http',
- url: 'https://sheetsmcp.googleapis.com/mcp/v1',
- oauth_header_key: 'Authorization',
- },
- },
- {
- id: 'gtasks',
- display_name: 'Google Tasks',
- icon_svg: '<svg viewBox="0 0 192 192" xmlns="http://www.w3.org/2000/svg"><path fill="#FBBC04" d="m139.8 60.6 19.5 19.5 32.7-32.6L172.5 28z"/><path fill="#34A853" d="M88.5 111.9 67 90.5l-19.6 19.6 41 41 84.1-84-19.5-19.6z"/><path fill="#1A73E8" d="M97 192c52.7 0 95.5-42.8 95.5-95.6 0-2.5-.2-5-.4-7.5-2 2.4-83 83-83 83l-41.7-41.7-67 67c17.3 17 41 27.8 67 27.8z"/><path fill="#188038" d="M30 162c-37.6-37.6-37.6-98.6 0-136.2s98.6-37.6 136.2 0z"/></svg>',
- category: 'productivity',
- description_zh: '把任务管理直接接入工作流。',
- description_en: 'Integrate task management directly into your workflows.',
- auth_mode: 'server_bridge',
- oauth: { provider_id: 'google' },
- transport_template: {
- kind: 'streamable-http',
- url: 'https://tasksmcp.googleapis.com/mcp/v1',
- oauth_header_key: 'Authorization',
- },
- },
+ // Google Workspace entries (`google-workspace` bundle + 5 service members) live in
+ // `catalog-google.ts` and are loaded via `_loadGoogleEntries` below — that file is
+ // **stripped from the OrkasOpen build** because Google's production OAuth verification +
+ // CASA assessment can't be satisfied for an OSS distribution (see
+ // `OpenSource/SyncCode/strip-rules.json` `forbidden_files`). PC ships them; OrkasOpen
+ // silently omits them (require throws → empty array).
+ ..._loadGoogleEntries(),
];
+function _loadGoogleEntries(): CatalogEntry[] {
+ try {
+ // `require` (not `import`) so the path isn't statically resolved at bundle time. In the
+ // OrkasOpen build the file is absent and the require throws — we swallow + return [].
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const mod = require('./catalog-google') as { GOOGLE_ENTRIES?: CatalogEntry[] };
+ return Array.isArray(mod.GOOGLE_ENTRIES) ? mod.GOOGLE_ENTRIES : [];
+ } catch {
+ return [];
+ }
+}
+
export function findCatalogEntry(id: string): CatalogEntry | null {
return CONNECTOR_CATALOG.find((e) => e.id === id) || null;
}
diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.ts
index 38bfa31d..f290b154 100644
--- a/src/main/features/connectors/manager.ts
+++ b/src/main/features/connectors/manager.ts
@@ -26,17 +26,120 @@ const log = createLogger('connectors:manager');
const _conns = new Map<string, McpConnection>();
let _bootedFor: string | null = null;
+/** Per-instance in-flight refresh dedupe. **Why:** OAuth refresh_tokens (GitHub App `ghr_*`,
+ * Notion DCR, etc.) ROTATE on every successful exchange — the old token is invalidated the
+ * moment the provider issues a new one. Two concurrent `_resolveTransport` calls (e.g. two
+ * parallel `call_connector_tool` invocations from one model turn, or `bootstrap` racing with
+ * a user-triggered tool call) would both POST the SAME stale refresh_token; the first wins
+ * and rotates → the second hits `bad_refresh_token` → its catch branch writes
+ * `status:error` → the connector is permanently broken until the user re-authorizes. The
+ * Map<instanceId, Promise<OAuthGrant>> coalesces concurrent callers onto a single in-flight
+ * request; subsequent calls await the same Promise, get the same new grant, and proceed
+ * identically. Lock entries auto-clear in the `finally` block so a failed refresh doesn't
+ * jam the slot. */
+const _refreshLocks = new Map<string, Promise<OAuthGrant>>();
+
+const REFRESH_BUFFER_MS = 5 * 60 * 1000;
+
function _now(): number { return Date.now(); }
function _nowIso(): string { return new Date().toISOString(); }
-async function _refreshGrantIfStale(uid: string, entry: CatalogEntry, inst: ConnectorInstance): Promise<OAuthGrant> {
- if (!inst.oauth_grant) throw new Error('no oauth_grant');
- if (entry.auth_mode === 'mcp_dcr') {
- if (!inst.dcr_client) throw new Error('DCR instance missing dcr_client credentials');
- return refreshDcrIfStale(inst.dcr_client, inst.oauth_grant);
+/** Truncated token fingerprint for diagnostic logs — first 12 chars is enough to correlate
+ * across PC + Server logs without leaking the full token. Returns 'none' for missing tokens
+ * and 'null' for the literal-null fallback some refresh endpoints emit. */
+function _tokPrefix(t: string | null | undefined): string {
+ if (!t) return 'none';
+ return t.slice(0, 12) + (t.length > 12 ? '…' : '');
+}
+
+/** Refresh the access_token if stale, dedupe concurrent callers, and persist the rotated grant
+ * atomically before returning. After taking the lock we re-READ the instance from disk —
+ * another caller that just released the lock may have written a new grant; using the caller's
+ * in-memory `inst` snapshot would re-trigger an unnecessary (and stale-token-using!) refresh.
+ *
+ * Diagnostic logging: every refresh attempt prints the RT prefix being sent so a future
+ * `bad_refresh_token` failure can be correlated with the exchange/refresh that originally
+ * issued that RT. Rotation (old → new RT prefix) is also logged so we can verify the new
+ * RT actually made it onto disk via the post-write read-back in `registry._writeSync`. */
+async function _refreshGrantIfStale(uid: string, entry: CatalogEntry, instId: string): Promise<OAuthGrant> {
+ const existing = _refreshLocks.get(instId);
+ if (existing) {
+ log.info('refresh dedupe hit', { id: instId });
+ return existing;
}
- // server_bridge default
- return refreshIfStale(uid, entry, inst.oauth_grant);
+ const p = (async () => {
+ try {
+ const inst = registry.load(uid).connections[instId];
+ if (!inst) throw new Error('instance not found');
+ if (!inst.oauth_grant) throw new Error('no oauth_grant');
+ // Already fresh? Skip the remote call entirely.
+ if (inst.oauth_grant.expires_at && inst.oauth_grant.expires_at - Date.now() > REFRESH_BUFFER_MS) {
+ return inst.oauth_grant;
+ }
+ const oldRt = inst.oauth_grant.refresh_token;
+ log.info('refresh attempt', {
+ id: instId,
+ auth_mode: entry.auth_mode,
+ rt_prefix: _tokPrefix(oldRt),
+ at_prefix: _tokPrefix(inst.oauth_grant.access_token),
+ expires_at_ms: inst.oauth_grant.expires_at,
+ ms_until_expiry: inst.oauth_grant.expires_at ? inst.oauth_grant.expires_at - Date.now() : null,
+ });
+ let next: OAuthGrant;
+ try {
+ if (entry.auth_mode === 'mcp_dcr') {
+ if (!inst.dcr_client) throw new Error('DCR instance missing dcr_client credentials');
+ next = await refreshDcrIfStale(inst.dcr_client, inst.oauth_grant);
+ } else {
+ next = await refreshIfStale(uid, entry, inst.oauth_grant);
+ }
+ } catch (err) {
+ log.warn('refresh upstream failed', {
+ id: instId,
+ rt_sent: _tokPrefix(oldRt),
+ error: (err as Error).message,
+ });
+ throw err;
+ }
+ const rotated = oldRt !== next.refresh_token;
+ log.info('refresh ok', {
+ id: instId,
+ old_rt: _tokPrefix(oldRt),
+ new_rt: _tokPrefix(next.refresh_token),
+ new_at: _tokPrefix(next.access_token),
+ rotated,
+ new_expires_at_ms: next.expires_at,
+ });
+ // Persist the rotated grant inside the lock so the next caller's re-read sees it. Use
+ // `update(patch)` not `upsert(snapshot)` — concurrent writers (status updates from a
+ // different code path) must not be clobbered by a stale field-set spread.
+ if (next !== inst.oauth_grant) {
+ try {
+ await registry.update(uid, instId, (cur) => ({
+ ...cur,
+ oauth_grant: next,
+ updated_at: _nowIso(),
+ }));
+ log.info('refresh grant persisted', {
+ id: instId,
+ new_rt: _tokPrefix(next.refresh_token),
+ });
+ } catch (err) {
+ log.error('refresh grant persist FAILED — disk RT now diverged from server', {
+ id: instId,
+ new_rt_on_server: _tokPrefix(next.refresh_token),
+ error: (err as Error).message,
+ });
+ throw err;
+ }
+ }
+ return next;
+ } finally {
+ _refreshLocks.delete(instId);
+ }
+ })();
+ _refreshLocks.set(instId, p);
+ return p;
}
async function _resolveTransport(uid: string, inst: ConnectorInstance): Promise<{ transport: Transport; grant: OAuthGrant } | null> {
@@ -51,67 +154,69 @@ async function _resolveTransport(uid: string, inst: ConnectorInstance): Promise<
}
let grant: OAuthGrant;
try {
- grant = await _refreshGrantIfStale(uid, entry, inst);
+ grant = await _refreshGrantIfStale(uid, entry, inst.id);
} catch (err) {
log.warn('refresh failed', { id: inst.id, error: (err as Error).message });
throw err;
}
- if (grant !== inst.oauth_grant) {
- // Persist rotated tokens before spawning so a crash here doesn't lose a refresh.
- await registry.update(uid, inst.id, (cur) => ({ ...cur, oauth_grant: grant, updated_at: _nowIso() }));
- }
const transport = applyTemplate(entry, grant);
return { transport, grant };
}
+/** Atomic patch of the per-instance status field. Used in every error / success branch below
+ * instead of `registry.upsert(snapshot)` to avoid clobbering fields written concurrently by
+ * the refresh path (most importantly `oauth_grant`). When the row was deleted between entry
+ * and patch (`removeInstance` raced us), `update` returns null and we fall back to the caller's
+ * stale `inst` — harmless since nobody downstream looks up by id again. */
+async function _patchStatus(
+ uid: string,
+ inst: ConnectorInstance,
+ patch: (cur: ConnectorInstance) => ConnectorInstance,
+): Promise<ConnectorInstance> {
+ const updated = await registry.update(uid, inst.id, patch);
+ return updated ?? inst;
+}
+
async function _connectAndCacheTools(uid: string, inst: ConnectorInstance): Promise<ConnectorInstance> {
let transport: Transport;
try {
const resolved = await _resolveTransport(uid, inst);
if (!resolved) {
- const updated: ConnectorInstance = {
- ...inst,
+ return _patchStatus(uid, inst, (cur) => ({
+ ...cur,
status: { kind: 'error', message: 'transport unresolved', at: _now() },
updated_at: _nowIso(),
- };
- await registry.upsert(uid, updated);
- return updated;
+ }));
}
transport = resolved.transport;
} catch (err) {
- const updated: ConnectorInstance = {
- ...inst,
+ return _patchStatus(uid, inst, (cur) => ({
+ ...cur,
status: { kind: 'error', message: (err as Error).message, at: _now() },
updated_at: _nowIso(),
- };
- await registry.upsert(uid, updated);
- return updated;
+ }));
}
const conn = new McpConnection(inst.id, transport);
try {
await conn.connect();
const tools = await conn.listTools();
_conns.set(inst.id, conn);
- const updated: ConnectorInstance = {
- ...inst,
+ return _patchStatus(uid, inst, (cur) => ({
+ ...cur,
transport,
tools_cache: tools,
tools_cached_at: _now(),
status: { kind: 'connected', since: _now() },
updated_at: _nowIso(),
- };
- await registry.upsert(uid, updated);
- return updated;
+ }));
} catch (err) {
log.warn('connect+list failed', { id: inst.id, error: (err as Error).message });
try { await conn.close(); } catch { /* swallow */ }
- const updated: ConnectorInstance = {
- ...inst,
+ return _patchStatus(uid, inst, (cur) => ({
+ ...cur,
status: { kind: 'error', message: (err as Error).message, at: _now() },
updated_at: _nowIso(),
- };
- await registry.upsert(uid, updated);
- return updated;
+ }));
}
}
@@ -153,9 +258,6 @@ export async function connectViaOAuth(uid: string, catalogId: string): Promise<C
if (!uid) throw new Error('uid required');
const entry = findCatalogEntry(catalogId);
if (!entry) throw new Error('unknown catalog id');
- if (!entry.transport_template) {
- throw new Error(`'${catalogId}' is not installable yet (${entry.unavailable_reason || 'unavailable'})`);
- }
log.info('connectViaOAuth: starting OAuth', { catalog_id: catalogId, auth_mode: entry.auth_mode });
let grant: OAuthGrant;
@@ -168,14 +270,56 @@ export async function connectViaOAuth(uid: string, catalogId: string): Promise<C
if (!entry.oauth) throw new Error(`'${catalogId}' has no oauth config`);
grant = await startOAuth(uid, entry);
}
+
+ // Bundle entry: one OAuth flow (the Server returns a grant with union scopes) → provision N
+ // member instances, each with its own transport and a deep-cloned grant. The bundle entry
+ // itself has `transport_template: null` and never becomes an instance — see CatalogEntry's
+ // `bundle_member_ids` doc.
+ if (entry.bundle_member_ids?.length) {
+ log.info('connectViaOAuth: bundle — provisioning members', {
+ bundle: catalogId,
+ members: entry.bundle_member_ids,
+ });
+ let firstMember: ConnectorInstance | null = null;
+ for (const memberId of entry.bundle_member_ids) {
+ const memberEntry = findCatalogEntry(memberId);
+ if (!memberEntry) { log.warn('bundle member missing from catalog', { memberId }); continue; }
+ if (!memberEntry.transport_template) { log.warn('bundle member has no transport template', { memberId }); continue; }
+ // Deep-clone so each member's `_refreshGrantIfStale` mutates its own copy when the token
+ // rotates. They independently re-hit the refresh endpoint (slight waste, ~5 refreshes/h
+ // per user — acceptable); the alternative is a shared refresh lock keyed by `refresh_token`
+ // which is a bigger lifecycle change.
+ const memberGrant: OAuthGrant = JSON.parse(JSON.stringify(grant));
+ const member = await _provisionMemberInstance(uid, memberEntry, memberGrant, dcrClient);
+ if (!firstMember) firstMember = member;
+ }
+ if (!firstMember) throw new Error('bundle produced no member instances');
+ return firstMember; // renderer reloads the full list after; the return value is informational
+ }
+
+ if (!entry.transport_template) {
+ throw new Error(`'${catalogId}' is not installable yet (${entry.unavailable_reason || 'unavailable'})`);
+ }
log.info('connectViaOAuth: OAuth done; spawning MCP server', { catalog_id: catalogId });
+ return _provisionMemberInstance(uid, entry, grant, dcrClient);
+}
+
+/** Provision (or replace) a single instance for a non-bundle catalog entry. Pulled out of
+ * `connectViaOAuth` so the bundle branch can loop over members. Caller has already obtained
+ * the OAuth grant. */
+async function _provisionMemberInstance(
+ uid: string,
+ entry: CatalogEntry,
+ grant: OAuthGrant,
+ dcrClient: ConnectorInstance['dcr_client'],
+): Promise<ConnectorInstance> {
const transport = applyTemplate(entry, grant);
// Tear down any prior live connection for the same id before re-using the slot.
- const prior = _conns.get(catalogId);
+ const prior = _conns.get(entry.id);
if (prior) {
try { await prior.close(); } catch { /* swallow */ }
- _conns.delete(catalogId);
+ _conns.delete(entry.id);
}
const draft: ConnectorInstance = {
@@ -191,6 +335,18 @@ export async function connectViaOAuth(uid: string, catalogId: string): Promise<C
created_at: _nowIso(),
updated_at: _nowIso(),
};
+ // Diagnostic: capture which RT just got issued by the provider so a later refresh failure
+ // can be matched against this exchange (the `_refreshGrantIfStale` logs print the same
+ // _tokPrefix shape — `bad_refresh_token` mid-day means the on-disk RT no longer matches
+ // what the provider has on record; correlating prefixes pinpoints whether the write here
+ // didn't land or got overwritten by another path).
+ log.info('provision: fresh grant from exchange', {
+ id: entry.id,
+ rt_prefix: _tokPrefix(grant.refresh_token),
+ at_prefix: _tokPrefix(grant.access_token),
+ expires_at_ms: grant.expires_at,
+ has_dcr_client: !!dcrClient,
+ });
await registry.upsert(uid, draft);
return _connectAndCacheTools(uid, draft);
}
@@ -240,10 +396,25 @@ export async function callTool(
args: Record<string, unknown>,
): Promise<unknown> {
if (!uid) throw new Error('uid required');
+ const inst = getInstance(uid, id);
+ if (!inst) throw new Error('instance not found');
+ // Stale-token guard: the transport snapshots the bearer at connect time (for streamable-http)
+ // or injects it into env at spawn time (for stdio). A long-lived connection past the
+ // `expires_at` deadline will keep using the dead token on every request — fine for short-lived
+ // chats (1h Gmail TTL is rarely exceeded inside one conversation) but breaks "leave PC open
+ // overnight" use cases. Detect staleness, tear down + reconnect; `_resolveTransport` calls
+ // `_refreshGrantIfStale` which rotates the token before applyTemplate rebuilds the transport
+ // with the fresh one. Same `REFRESH_BUFFER_MS` window the refresh path uses.
+ const grant = inst.oauth_grant;
+ const stale = !!(grant && grant.expires_at && grant.expires_at - Date.now() <= REFRESH_BUFFER_MS);
let conn = _conns.get(id);
+ if (stale && conn) {
+ log.info('grant stale → tearing down to refresh on reconnect', { id });
+ try { await conn.close(); } catch { /* swallow */ }
+ _conns.delete(id);
+ conn = undefined;
+ }
if (!conn || !conn.isConnected) {
- const inst = getInstance(uid, id);
- if (!inst) throw new Error('instance not found');
const resolved = await _resolveTransport(uid, inst);
if (!resolved) throw new Error('transport unresolved');
conn = new McpConnection(id, resolved.transport);
diff --git a/src/main/features/connectors/registry.ts b/src/main/features/connectors/registry.ts
index 30c0c98f..68db6e4c 100644
--- a/src/main/features/connectors/registry.ts
+++ b/src/main/features/connectors/registry.ts
@@ -1,30 +1,137 @@
/**
* Persistence for the connectors registry.
*
- * Single-file JSON at `<uid>/local/config/connectors.json` (see `paths.ts::userConnectorsConfigFile`),
- * encrypted via `crypto-vault.ts` (PBKDF2-derived AES-256-GCM). Plaintext-fallback on read for
- * forward compatibility with files written by an earlier (Phase 0 alpha) version of this module;
- * detected plaintext is parsed and immediately re-written as ciphertext on the next save.
+ * Single-file JSON at `<uid>/cloud/config/connectors.json` (see `paths.ts::userConnectorsConfigFile`).
+ * **File body is plaintext JSON**; each instance's sensitive blob (`oauth_grant` + `dcr_client` +
+ * `transport`) is packed into a single per-instance `secrets_enc` field encrypted via
+ * `util/crypto-vault.ts` (PBKDF2 → AES-256-GCM). Metadata fields (`display_name` / `status` /
+ * `tools_cache` / timestamps) stay plaintext so Server-side iOS-clients-facing readers can list
+ * connectors without holding the vault key. `transport` sits in the secrets blob even though it
+ * isn't a "secret" by name — `applyTemplate` bakes the resolved `access_token` into
+ * `transport.env[oauth_env_key]` (stdio) / `transport.headers.Authorization` (streamable-http);
+ * leaving it plaintext would defeat the whole encryption. Runtime cost is zero:
+ * `manager.ts::_resolveTransport` re-runs `applyTemplate` from the catalog template + fresh
+ * `oauth_grant` on every connect, so the persisted transport is purely vestigial. The read path
+ * also accepts the legacy whole-file vault format produced by pre-LOCAL_DATA_VERSION=2 builds;
+ * the next write naturally upgrades the file in place.
*
- * Why encrypted on disk: stores OAuth bearer tokens. Even though the crypto is "obfuscation-grade"
- * (key derivable from uid alone), it covers the realistic threat surface — backup tooling, log
- * grep, sync corner cases — see `crypto-vault.ts` header.
+ * **Vault seed = Orkas-account OAuth user_id (when logged in), else local uid**. Same OAuth
+ * user_id on every device the user signs into → cross-device decryption after cloud sync.
+ * OrkasOpen / not-logged-in falls back to local uid (file then sits in cloud/config/ but the
+ * sync engine is inactive without an account, so it stays machine-private de facto). See
+ * `_vaultSeed` for the resolution.
+ *
+ * Sync trigger: each write fires `syncFeature.markDirty('connectors', 'cloud/config/connectors.json')`
+ * so user actions (install / disconnect / refresh) push within the debounce window rather than
+ * waiting for the 5-min periodic. Like sync itself, gracefully no-ops in builds that strip
+ * `features/sync` (OrkasOpen).
*
* All writes are serialized via async-mutex so two concurrent IPC calls can't race-overwrite.
*/
import * as fs from 'node:fs';
+import * as path from 'node:path';
import { Mutex } from 'async-mutex';
-import { userConnectorsConfigFile, userLocalConfigDir } from '../../paths';
+import { userConnectorsConfigFile } from '../../paths';
import { createLogger } from '../../logger';
import * as cryptoVault from '../../util/crypto-vault';
-import type { ConnectorInstance, ConnectorsFile } from './types';
+import type { ConnectorInstance, ConnectorsFile, OAuthGrant, DcrClientCredentials, Transport } from './types';
const log = createLogger('connectors:registry');
const _writeMutex = new Mutex();
const EMPTY: ConnectorsFile = { version: 1, connections: {} };
+// On-disk shape: ConnectorInstance with all token-bearing fields collapsed into one
+// vault-encrypted `secrets_enc` string. **`transport` is in the blob too** — even though it's
+// not a "secret" by name, `applyTemplate` bakes the resolved `access_token` into
+// `transport.env[oauth_env_key]` (stdio) / `transport.headers.Authorization` (streamable-http);
+// leaving it plaintext on disk would defeat the whole encryption. `manager.ts::_resolveTransport`
+// re-runs `applyTemplate` from the catalog template + fresh `oauth_grant` on every connect, so
+// the persisted transport is purely vestigial at runtime — sealing it has zero runtime cost.
+// Only this module is aware of the disk form.
+type InstanceOnDisk = Omit<ConnectorInstance, 'oauth_grant' | 'dcr_client' | 'transport'> & {
+ secrets_enc?: string;
+ // Kept optional in the disk type so a hydrate failure can still surface a row (with `transport`
+ // unset and oauth_grant unset) — manager will mark it `status:error` and the user re-OAuths.
+};
+interface SecretsBlob { oauth_grant?: OAuthGrant; dcr_client?: DcrClientCredentials; transport?: Transport }
+
+// Vault-seed resolver. Tries the Orkas account's OAuth user_id (cross-device decryptable);
+// falls back to local uid for OrkasOpen / pre-login. Lazy require because `features/account`
+// is stripped from the OrkasOpen build — a static import would break that build at module-load
+// time. Same defensive pattern as `catalog.ts::_loadGoogleEntries`.
+function _vaultSeed(uid: string): string {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const account = require('../account') as { oauthUserId?: () => string | null };
+ const oauth = account.oauthUserId?.();
+ if (oauth) return oauth;
+ } catch { /* features/account stripped → fall through */ }
+ return uid;
+}
+
+// Same lazy-require for the sync engine — OrkasOpen strips `features/sync`, so a static import
+// would break the build. When sync is absent, `_notifyDirty` is a no-op and writes go through
+// without the immediate-sync nudge (the file still syncs eventually via the 5-min periodic /
+// before-quit on builds that DO have sync; OrkasOpen never syncs at all).
+function _notifyDirty(): void {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const sync = require('../sync') as { markDirty?: (domain: string, relPath: string) => void };
+ sync.markDirty?.('connectors', 'cloud/config/connectors.json');
+ } catch { /* features/sync stripped */ }
+}
+
+// Decrypt with the active seed; fall back to local-uid for files written before the
+// 2026-05-15 cloud-sync rekey OR for OrkasOpen / pre-login users who only ever had the
+// local-uid encryption path. AES-GCM's auth tag makes wrong-key attempts throw cleanly — no
+// plaintext leakage.
+function _tryDecrypt(uid: string, payload: string): string | null {
+ const primary = _vaultSeed(uid);
+ try { return cryptoVault.decrypt(primary, payload); } catch { /* try fallback */ }
+ if (primary !== uid) {
+ try { return cryptoVault.decrypt(uid, payload); } catch { /* both failed */ }
+ }
+ return null;
+}
+
+function _hydrateSecrets(uid: string, disk: InstanceOnDisk): ConnectorInstance {
+ const { secrets_enc, ...rest } = disk;
+ // transport is required on ConnectorInstance but absent from the disk shape — it lives in the
+ // secrets blob. Cast through; manager.ts handles the no-transport / no-grant case via
+ // `_resolveTransport` returning null → status:error.
+ const out = { ...rest } as ConnectorInstance;
+ if (!secrets_enc) return out;
+ const json = _tryDecrypt(uid, secrets_enc);
+ if (json === null) {
+ log.warn('decrypt secrets_enc failed (both seeds) — instance left without transport/grant', { id: disk.id });
+ return out;
+ }
+ try {
+ const blob = JSON.parse(json) as SecretsBlob;
+ if (blob.oauth_grant) out.oauth_grant = blob.oauth_grant;
+ if (blob.dcr_client) out.dcr_client = blob.dcr_client;
+ if (blob.transport) out.transport = blob.transport;
+ } catch (err) {
+ log.warn('parse secrets_enc payload failed', { id: disk.id, error: (err as Error).message });
+ }
+ return out;
+}
+
+function _dehydrateSecrets(uid: string, inst: ConnectorInstance): InstanceOnDisk {
+ const { oauth_grant, dcr_client, transport, ...rest } = inst;
+ const onDisk = { ...rest } as InstanceOnDisk;
+ if (oauth_grant || dcr_client || transport) {
+ const blob: SecretsBlob = {};
+ if (oauth_grant) blob.oauth_grant = oauth_grant;
+ if (dcr_client) blob.dcr_client = dcr_client;
+ if (transport) blob.transport = transport;
+ onDisk.secrets_enc = cryptoVault.encrypt(_vaultSeed(uid), JSON.stringify(blob));
+ }
+ return onDisk;
+}
+
function _readSync(uid: string): ConnectorsFile {
const file = userConnectorsConfigFile(uid);
let raw: string;
@@ -38,17 +145,35 @@ function _readSync(uid: string): ConnectorsFile {
return { version: 1, connections: {} };
}
if (!raw.trim()) return { version: 1, connections: {} };
- let json: string;
- try {
- json = cryptoVault.isEncryptedPayload(raw) ? cryptoVault.decrypt(uid, raw) : raw;
- } catch (err) {
- log.warn('decrypt connectors.json failed', { error: (err as Error).message });
+
+ // Legacy whole-file vault format: decrypt once, plaintext JSON already has oauth_grant /
+ // dcr_client as plain fields per instance — return as-is. Next write upgrades to per-field.
+ if (cryptoVault.isEncryptedPayload(raw)) {
+ const json = _tryDecrypt(uid, raw);
+ if (json === null) {
+ log.warn('decrypt connectors.json (legacy whole-file) failed with both seeds — treating as empty');
+ return { version: 1, connections: {} };
+ }
+ try {
+ const obj = JSON.parse(json);
+ if (obj && typeof obj === 'object' && obj.connections && typeof obj.connections === 'object') {
+ return { version: 1, connections: obj.connections as Record<string, ConnectorInstance> };
+ }
+ } catch (err) {
+ log.warn('parse connectors.json (legacy whole-file) failed', { error: (err as Error).message });
+ }
return { version: 1, connections: {} };
}
+
+ // Current format: plaintext JSON envelope, secrets_enc per instance.
try {
- const obj = JSON.parse(json);
+ const obj = JSON.parse(raw);
if (obj && typeof obj === 'object' && obj.connections && typeof obj.connections === 'object') {
- return { version: 1, connections: obj.connections as Record<string, ConnectorInstance> };
+ const conns: Record<string, ConnectorInstance> = {};
+ for (const [id, disk] of Object.entries(obj.connections as Record<string, InstanceOnDisk>)) {
+ conns[id] = _hydrateSecrets(uid, disk);
+ }
+ return { version: 1, connections: conns };
}
} catch (err) {
log.warn('parse connectors.json failed', { error: (err as Error).message });
@@ -59,9 +184,31 @@ function _readSync(uid: string): ConnectorsFile {
function _writeSync(uid: string, data: ConnectorsFile): void {
const file = userConnectorsConfigFile(uid);
try {
- fs.mkdirSync(userLocalConfigDir(uid), { recursive: true });
- const enc = cryptoVault.encrypt(uid, JSON.stringify(data, null, 2));
- fs.writeFileSync(file, enc, { mode: 0o600 });
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const onDisk: Record<string, InstanceOnDisk> = {};
+ for (const [id, inst] of Object.entries(data.connections)) {
+ onDisk[id] = _dehydrateSecrets(uid, inst);
+ }
+ const body = JSON.stringify({ version: 2, connections: onDisk }, null, 2);
+ fs.writeFileSync(file, body, { mode: 0o600 });
+ // Diagnostic verify: read back size + the secrets_enc fingerprints we just wrote so a
+ // future "the RT we sent doesn't match server" failure can be traced against actual
+ // bytes on disk at write time. `secrets_enc` is the AES-GCM blob; comparing its first
+ // 16 chars across log entries reveals whether a subsequent write clobbered this one.
+ try {
+ const st = fs.statSync(file);
+ const fingerprints: Record<string, string> = {};
+ for (const [id, disk] of Object.entries(onDisk)) {
+ if (disk.secrets_enc) fingerprints[id] = disk.secrets_enc.slice(0, 16);
+ }
+ log.info('connectors.json write ok', {
+ bytes: st.size,
+ mtime_ms: st.mtimeMs,
+ secrets_enc_prefix: fingerprints,
+ });
+ } catch (verifyErr) {
+ log.warn('write verify (stat) failed', { error: (verifyErr as Error).message });
+ }
} catch (err) {
log.error('failed to persist connectors.json', { error: (err as Error).message });
throw err;
@@ -73,22 +220,40 @@ export function load(uid: string): ConnectorsFile {
return _readSync(uid);
}
+/** Compact RT fingerprint for diagnostic logs across the registry call chain. */
+function _rt(grant: ConnectorInstance['oauth_grant']): string {
+ const t = grant?.refresh_token;
+ if (!t) return 'none';
+ return t.slice(0, 12) + (t.length > 12 ? '…' : '');
+}
+
export async function upsert(uid: string, inst: ConnectorInstance): Promise<void> {
await _writeMutex.runExclusive(async () => {
const cur = _readSync(uid);
+ const before = cur.connections[inst.id];
+ log.info('registry.upsert', {
+ id: inst.id,
+ rt_before: _rt(before?.oauth_grant),
+ rt_after: _rt(inst.oauth_grant),
+ had_existing: !!before,
+ });
cur.connections[inst.id] = inst;
_writeSync(uid, cur);
});
+ _notifyDirty();
}
export async function remove(uid: string, id: string): Promise<boolean> {
- return _writeMutex.runExclusive(async () => {
+ const removed = await _writeMutex.runExclusive(async () => {
const cur = _readSync(uid);
if (!cur.connections[id]) return false;
+ log.info('registry.remove', { id, rt_before: _rt(cur.connections[id].oauth_grant) });
delete cur.connections[id];
_writeSync(uid, cur);
return true;
});
+ if (removed) _notifyDirty();
+ return removed;
}
export async function update(
@@ -96,15 +261,23 @@ export async function update(
id: string,
patch: (inst: ConnectorInstance) => ConnectorInstance,
): Promise<ConnectorInstance | null> {
- return _writeMutex.runExclusive(async () => {
+ const next = await _writeMutex.runExclusive(async () => {
const cur = _readSync(uid);
const existing = cur.connections[id];
if (!existing) return null;
- const next = patch(existing);
- cur.connections[id] = next;
+ const updated = patch(existing);
+ log.info('registry.update', {
+ id,
+ rt_before: _rt(existing.oauth_grant),
+ rt_after: _rt(updated.oauth_grant),
+ rt_changed: existing.oauth_grant?.refresh_token !== updated.oauth_grant?.refresh_token,
+ });
+ cur.connections[id] = updated;
_writeSync(uid, cur);
- return next;
+ return updated;
});
+ if (next) _notifyDirty();
+ return next;
}
export function isValidInstanceId(id: unknown): id is string {
diff --git a/src/main/features/connectors/tools-adapter.ts b/src/main/features/connectors/tools-adapter.ts
index 65d7b249..40f921c9 100644
--- a/src/main/features/connectors/tools-adapter.ts
+++ b/src/main/features/connectors/tools-adapter.ts
@@ -24,6 +24,7 @@
*/
import * as manager from './manager';
import * as agents from '../agents';
+import { isConnectorEnabled } from '../component_enabled';
import type { ConnectorInstance, ToolSchema } from './types';
/** Convert MCP `callTool`'s raw result into a single string the LLM can read.
@@ -57,7 +58,20 @@ export async function resolveVisibleConnectors(
if (!uid) return [];
const all = manager.listInstances(uid);
if (!all.length) return [];
- const scope = await _enabledInstancesForActor(uid, agentId, all);
+ // Live-state filter: only currently-connected instances surface to the LLM. A `connecting` /
+ // `disconnected` / `error` instance is unreachable in this turn — `manager.callTool` would
+ // throw anyway, and showing it (with a "— disconnected (ask user to refresh)" suffix) is
+ // noise that pollutes both the prompt block and the meta-tool routing matrix. The user can
+ // reconnect in the Connectors panel; the instance reappears on the next turn.
+ const connected = all.filter((i) => i.status.kind === 'connected');
+ if (!connected.length) return [];
+ // Per-user soft-disable filter (Connectors panel "停用" button). Separate from `agent.enabled_connectors`:
+ // this filter applies to every actor including the commander; even a disconnected-by-user instance
+ // that's still OAuth-grant-valid and MCP-connected stays hidden from the LLM until re-enabled.
+ // See features/component_enabled.ts + CLAUDE.md §6.5 "Per-user enable toggle".
+ const userEnabled = connected.filter((i) => isConnectorEnabled(uid, i.id));
+ if (!userEnabled.length) return [];
+ const scope = await _enabledInstancesForActor(uid, agentId, userEnabled);
return scope.map((instance) => {
const allowed = instance.enabled_subtools;
const tools = allowed === null
diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.ts
index c5699990..ed9b90a2 100644
--- a/src/main/features/connectors/types.ts
+++ b/src/main/features/connectors/types.ts
@@ -195,4 +195,13 @@ export interface CatalogEntry {
transport_template: TransportTemplate | null;
/** Set when `transport_template` is null to explain why; renderer surfaces in the badge. */
unavailable_reason?: 'oauth_pending';
+ /** When set, this catalog entry is a **UI-only bundle**: one OAuth flow provisions N member
+ * ConnectorInstances (one per listed catalog id). The bundle entry itself does NOT produce a
+ * ConnectorInstance and has `transport_template: null` — the model sees the members as
+ * independent connectors with their own tools. Renderer shows a single bundle card and
+ * hides the member entries. The bundle's OAuth `catalog_id` triggers the server-side
+ * scope-union path (e.g. `google-workspace` requests all 5 Google service scopes at once),
+ * and the manager clones the resulting grant into each member instance. See
+ * `manager.ts::connectViaOAuth`. */
+ bundle_member_ids?: string[];
}
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 6a5ff4a6..ab44721b 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -808,7 +808,7 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
emit(state, { type: 'state_changed', cid, state: await readState(uid, cid) });
log.info(`turn-start user=${uid} cid=${cid} actor=${actor.id} kind=${actor.kind} fromMsg=${item.msgId} from=${item.fromActorId}`);
- const sessionId = actorSessionId(uid, cid, actor);
+ const sessionId = actorSessionId(cid, actor);
const isCommander = actor.kind === 'commander';
// Per-conv subdir under the user's root workspace — keeps repeat
// agent runs writing the same basename grouped together instead of
diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.ts
index df057120..15f54b0a 100644
--- a/src/main/features/group_chat/state.ts
+++ b/src/main/features/group_chat/state.ts
@@ -94,23 +94,25 @@ export const USER_ID = 'user';
export const RESERVED_IDS: ReadonlySet<string> = new Set([COMMANDER_ID, USER_ID]);
// ── session_id builders ──────────────────────────────────────────────────
+// Format: `<kind>-<tail>` (CLAUDE.md §5). User scoping comes from the path root
+// (`<activeUid>/{cloud,local}/sessions/<sid>.jsonl`), not from the session_id.
/** Commander session — one per conversation, shared across all turns. */
-export function buildGconvSessionId(uid: string, cid: string): string {
- return `${uid}-gconv-${cid}`;
+export function buildGconvSessionId(cid: string): string {
+ return `gconv-${cid}`;
}
/** Per-agent session — one per (conv, agent), shared across all the agent's
* turns in that conv. */
-export function buildGmemberSessionId(uid: string, cid: string, agentId: string): string {
- return `${uid}-gmember-${cid}-${agentId}`;
+export function buildGmemberSessionId(cid: string, agentId: string): string {
+ return `gmember-${cid}-${agentId}`;
}
/** Resolve an actor's session id from its kind/id. The user actor has no
* session — it's the human. Throws on unknown kind. */
-export function actorSessionId(uid: string, cid: string, actor: Actor): string {
- if (actor.kind === 'commander') return buildGconvSessionId(uid, cid);
- if (actor.kind === 'agent') return buildGmemberSessionId(uid, cid, actor.id);
+export function actorSessionId(cid: string, actor: Actor): string {
+ if (actor.kind === 'commander') return buildGconvSessionId(cid);
+ if (actor.kind === 'agent') return buildGmemberSessionId(cid, actor.id);
throw new Error(`actor ${actor.kind}/${actor.id} has no session`);
}
diff --git a/src/main/features/kb_indexer.ts b/src/main/features/kb_indexer.ts
index b9b59b4c..d09271c4 100644
--- a/src/main/features/kb_indexer.ts
+++ b/src/main/features/kb_indexer.ts
@@ -298,7 +298,7 @@ async function extractChunks(uid: string, relPath: string, buf: Buffer, kind: kb
// burns tokens + tempts the model to mis-call them.
async function describeImage(userId: string, sourceName: string, raw: Buffer): Promise<string> {
const compressed = await toCompressedGrayJpeg(raw, { maxDim: 1024, quality: 70, grayscale: true });
- const sessionId = `${userId}-extract-img-${crypto.randomBytes(4).toString('hex')}`;
+ const sessionId = `extract-img-${crypto.randomBytes(4).toString('hex')}`;
const message = prompts.load('contexts_extract_image', { source_name: sourceName });
const r = await chatWithModel({
userId,
diff --git a/src/main/features/local_agents/runner.ts b/src/main/features/local_agents/runner.ts
index f3e5b815..3f035e14 100644
--- a/src/main/features/local_agents/runner.ts
+++ b/src/main/features/local_agents/runner.ts
@@ -173,7 +173,7 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
// CLI dispatch session id (matches the devtools-archive session id
// built below). The per-session spill dir is anchored on this so
// sweep / read paths can find the file again.
- const cliSessionId = `${opts.uid}-cli-${opts.cli}-${handle.runId}`;
+ const cliSessionId = `cli-${opts.cli}-${handle.runId}`;
const spillDir = sessionToolResultsDir(opts.uid, cliSessionId);
let lastEventAt = Date.now();
const onEvent = (e: LocalEvent) => {
@@ -276,6 +276,49 @@ export async function run(opts: RunCliAgentOpts): Promise<RunCliAgentResult> {
});
// The per-run jsonl under `local-agent-runs/<runId>/` (written by
// `persist`) is the only post-run artifact.
+ // prod and self-catches all errors, so we don't await or guard here.
+ // Devtools archive shape — keep the session_id format `<uid>-cli-<tail>`
+ // to match the §5 security invariant (uid first segment, kind second);
+ // `cli` is the new kind devtools recognises and badges as such.
+ // Provider = brand label ("Claude Code" / "Codex" ...) so the panel
+ // shows the human-readable CLI name; model = version string when
+ // detected, falling back to the user-picked model id, falling back
+ // to "(default)".
+ const brand = _cliBrandLabel(opts.cli);
+ const modelDisplay = entry.version
+ ? `${entry.version}${opts.model ? ` · ${opts.model}` : ''}`
+ : (opts.model || '(default)');
+ // Date-prefixed id matching the LLM-archive convention. Without
+ // it, archive filenames mix random-hex (CLI runId) with
+ // date-prefixed (LLM newArchiveId) and the lexicographic sort in
+ // `listFilesDesc` puts hex BEFORE dates regardless of when the
+ // run actually happened — the panel ends up out of order AND the
+ // 30-slot prune drops recent LLM calls. The runtime runId is
+ // preserved separately on `local-agent-runs/<runId>/`.
+ id: newArchiveId(new Date(startedAtMs)),
+ startedAt: startedAtIso,
+ endedAt: new Date(endedAtMs).toISOString(),
+ durationMs: endedAtMs - startedAtMs,
+ userId: opts.uid,
+ sessionId: `cli-${opts.cli}-${handle.runId}`,
+ input: {
+ message: opts.prompt,
+ provider: brand,
+ model: modelDisplay,
+ },
+ context: {
+ agentId: opts.agentId,
+ cid: opts.cid,
+ workingDir: opts.cwd,
+ hasAbortSignal: true,
+ },
+ events: archiveEvents,
+ output: {
+ text: finalOutput,
+ aborted: terminal.status === 'cancelled',
+ error: terminal.error || null,
+ },
+ });
return { runId: handle.runId, status: terminal.status, output: finalOutput, error: terminal.error };
}
diff --git a/src/main/features/memory.ts b/src/main/features/memory.ts
index f39e806c..81e26f90 100644
--- a/src/main/features/memory.ts
+++ b/src/main/features/memory.ts
@@ -274,7 +274,7 @@ export async function extractAndSaveCompactFacts(
const result = await chatWithModel({
userId,
message: extractPrompt,
- sessionId: `${userId}-memory-extract-${Date.now()}`,
+ sessionId: `memory-extract-${Date.now()}`,
systemPrompt: 'You are a fact extraction assistant. Follow the instructions strictly and do not add any extra content.',
});
diff --git a/src/main/features/projects.ts b/src/main/features/projects.ts
index 7f35d9d1..108ae29a 100644
--- a/src/main/features/projects.ts
+++ b/src/main/features/projects.ts
@@ -168,6 +168,7 @@ async function _readProject(uid: string, pid: string): Promise<Project | null> {
async function _writeProject(uid: string, p: Project): Promise<void> {
fs.mkdirSync(projectDir(uid, p.project_id), { recursive: true });
await writeJson(projectMetaFile(uid, p.project_id), p);
+ _notifyDirty();
}
function _normaliseBindings(raw: any): ProjectBindings {
@@ -192,6 +193,19 @@ async function _readBindings(uid: string, pid: string): Promise<ProjectBindings>
async function _writeBindings(uid: string, pid: string, b: ProjectBindings): Promise<void> {
fs.mkdirSync(projectDir(uid, pid), { recursive: true });
await writeJson(projectBindingsFile(uid, pid), b);
+ _notifyDirty();
+}
+
+// Sync engine dirty signal (lazy-require — `features/sync` is stripped from OrkasOpen). Mirrors
+// the pattern in `agents.ts::_invalidateAgentListCache`: any write to a `cloud/projects/...`
+// file should kick the sync debounce so the change propagates within seconds rather than the
+// 5-min periodic.
+function _notifyDirty(): void {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const sync = require('./sync') as { markDirty?: (domain: string, relPath: string) => void };
+ sync.markDirty?.('projects', 'cloud/projects');
+ } catch { /* features/sync stripped */ }
}
// ── Validation ────────────────────────────────────────────────────────────
diff --git a/src/main/features/reflection-trigger.ts b/src/main/features/reflection-trigger.ts
index 5ab7ef13..2be6d833 100644
--- a/src/main/features/reflection-trigger.ts
+++ b/src/main/features/reflection-trigger.ts
@@ -126,7 +126,7 @@ async function realReflectForAgent(uid: string, agentId: string, sinceMs: number
// created by buildRunner stays empty. Acceptable: same pattern as
// organizer/extract-img kinds (§5).
const tail = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
- const sessionId = `${uid}-reflect-${tail}`;
+ const sessionId = `reflect-${tail}`;
const { runner } = await buildRunner({
sessionId,
diff --git a/src/main/features/sessions_sweep.ts b/src/main/features/sessions_sweep.ts
index 7b5b6759..ed083ffd 100644
--- a/src/main/features/sessions_sweep.ts
+++ b/src/main/features/sessions_sweep.ts
@@ -47,7 +47,6 @@ const LEGACY_KINDS = new Set(['sub', 'organizer', 'conv']);
interface SweepResult {
scanned: number;
- alien_uid: number; // prefix doesn't match the active uid — session-store can never read these
orphan_cid: number; // gconv/gmember whose cid is no longer registered
ephemeral_on_cloud: number; // ephemeral kinds that leaked into cloud/sessions/
legacy: number; // sub / organizer / conv leftovers
@@ -55,30 +54,29 @@ interface SweepResult {
errors: number;
}
-// Pull the kind segment out of `<uid>-<kind>-<tail>`, accounting for
-// multi-segment kinds (extract-img / memory-extract). Returns null when the
-// id doesn't fit `<uid>-...` shape.
-function classify(userId: string, baseName: string): { kind: string; cid?: string } | null {
- if (!baseName.startsWith(`${userId}-`)) return null;
- const tail = baseName.slice(userId.length + 1);
- if (!tail) return null;
- // Match against multi-segment kinds first (longest match wins) — order
- // matters: `extract-img-abc` would also start with `extract` (a non-kind
- // prefix), but we don't list `extract` as a kind anymore.
+// Pull the kind segment out of `<kind>-<tail>` (CLAUDE.md §5; uid is no longer in session_id).
+// Multi-segment kinds (extract-img / memory-extract) are recognized longest-first. Returns
+// null when the basename doesn't start with any known kind keyword (caller skips it — usually
+// a leftover from a half-completed legacy migration).
+function classify(baseName: string): { kind: string; cid?: string } | null {
+ if (!baseName) return null;
+ // Match against multi-segment kinds first (longest match wins) — order matters: `extract-img-abc`
+ // starts with `extract` (a non-kind prefix), and `memory-extract-x` would otherwise match
+ // `memory` (also not a kind).
for (const k of ['extract-img', 'memory-extract']) {
- if (tail.startsWith(`${k}-`)) return { kind: k };
+ if (baseName === k) return { kind: k };
+ if (baseName.startsWith(`${k}-`)) return { kind: k };
}
- // For gconv/gmember/skill/agent/reflect/anon and legacy sub/organizer/conv:
- // single-segment kind, the rest is the tail (cid / aid / sid / random).
- const dash = tail.indexOf('-');
- if (dash < 0) return { kind: tail };
- const kind = tail.slice(0, dash);
- const rest = tail.slice(dash + 1);
+ // Single-segment kind, the rest is the tail (cid / aid / sid / random).
+ const dash = baseName.indexOf('-');
+ if (dash < 0) return { kind: baseName };
+ const kind = baseName.slice(0, dash);
+ const rest = baseName.slice(dash + 1);
if (kind === 'gconv') return { kind, cid: rest };
if (kind === 'gmember') {
- // gmember tail is `<cid>-<aid>`. Split the cid out by taking everything
- // up to the LAST dash. (cids today are 12-hex and contain no dashes; the
- // last-dash split is robust to that and to any future cid shape.)
+ // gmember tail is `<cid>-<aid>`. Split the cid out by taking everything up to the LAST
+ // dash. (cids today are 12-hex and contain no dashes; the last-dash split is robust to
+ // that and to any future cid shape.)
const lastDash = rest.lastIndexOf('-');
if (lastDash < 0) return { kind, cid: rest };
return { kind, cid: rest.slice(0, lastDash) };
@@ -110,32 +108,13 @@ async function sweepCloud(userId: string, result: SweepResult): Promise<void> {
result.scanned++;
const sid = name.slice(0, -'.jsonl'.length);
- // 1. Alien-uid prefix: the file lives under the active uid's sessions/
- // dir but its session_id starts with a different uid. session-store's
- // hard assertion (sessionFileFor: id MUST start with `<activeUid>-`)
- // means these are unreachable from any code path — pure dead state.
- // Historical cause on dev boxes: when the uid format moved from
- // 8-digit numeric to UUID, the data root carried over but sessions
- // were never renamed; the 8-digit-prefix files persisted, taking up
- // ~90% of the directory. Reading from them is impossible, so the
- // safest treatment is to drop them.
- if (!sid.startsWith(`${userId}-`)) {
- try {
- await fsp.unlink(path.join(dir, name));
- result.alien_uid++;
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
- log.warn(`unlink alien ${name}: ${(err as Error).message}`);
- result.errors++;
- }
- }
- continue;
- }
-
- const info = classify(userId, sid);
+ // session_id is now `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id).
+ // Files with any other shape are leftovers from before the migration and should already
+ // have been renamed by `migrateLegacySessionIds`; classify() returns null for them.
+ const info = classify(sid);
if (!info) continue;
let reason: keyof Pick<SweepResult, 'orphan_cid' | 'ephemeral_on_cloud' | 'legacy'> | null = null;
- if (isEphemeralSessionId(userId, sid)) {
+ if (isEphemeralSessionId(sid)) {
reason = 'ephemeral_on_cloud';
} else if (LEGACY_KINDS.has(info.kind)) {
reason = 'legacy';
@@ -189,18 +168,17 @@ async function sweepLocalByAge(userId: string, result: SweepResult, now: number)
export async function sweepSessions(userId: string): Promise<SweepResult> {
const t0 = Date.now();
const result: SweepResult = {
- scanned: 0, alien_uid: 0, orphan_cid: 0, ephemeral_on_cloud: 0, legacy: 0,
+ scanned: 0, orphan_cid: 0, ephemeral_on_cloud: 0, legacy: 0,
local_aged_out: 0, errors: 0,
};
await sweepCloud(userId, result);
await sweepLocalByAge(userId, result, Date.now());
- const removed = result.alien_uid + result.orphan_cid + result.ephemeral_on_cloud
+ const removed = result.orphan_cid + result.ephemeral_on_cloud
+ result.legacy + result.local_aged_out;
if (removed > 0 || result.errors > 0) {
log.info('sweep complete', {
uid: userId,
scanned: result.scanned,
- alien_uid: result.alien_uid,
orphan_cid: result.orphan_cid,
ephemeral_on_cloud: result.ephemeral_on_cloud,
legacy: result.legacy,
diff --git a/src/main/features/skills.ts b/src/main/features/skills.ts
index 11837d1c..98f58d6d 100644
--- a/src/main/features/skills.ts
+++ b/src/main/features/skills.ts
@@ -246,7 +246,17 @@ function skillBaseDir(source: SkillSource): string {
interface SkillListCache { stamp: string; data: SkillListing[] }
let _skillListCache: SkillListCache | null = null;
-function _invalidateSkillListCache(): void { _skillListCache = null; }
+function _invalidateSkillListCache(): void {
+ _skillListCache = null;
+ // Sync engine dirty signal (lazy-require — stripped in OrkasOpen). Mirrors the pattern in
+ // `agents.ts::_invalidateAgentListCache`: every cache-invalidate is also a disk-mutation
+ // point, co-locating keeps wiring tight.
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const sync = require('./sync') as { markDirty?: (domain: string, relPath: string) => void };
+ sync.markDirty?.('skills', 'cloud/skills');
+ } catch { /* features/sync stripped */ }
+}
/** Internal cache invalidator + core-agent registry invalidator. Exported for
* the dev-only `skills_dev` module so its dual-write path goes through the
@@ -643,13 +653,13 @@ export async function updateCustomSkill(
invalidateLineCount(path.join(oldChatDir, 'chat.jsonl'));
invalidateLineCount(path.join(newChatDir, 'chat.jsonl'));
const m = await loadSkillChatMeta(uid, newName);
- m.session_id = defaultSkillSessionId(uid, newName);
+ m.session_id = defaultSkillSessionId(newName);
await saveSkillChatMeta(uid, newName, m);
} catch (err) {
log.warn(`rename user=${uid} ${oldChatDir} -> ${newChatDir} failed: ${(err as Error).message}`);
}
}
- const oldSid = defaultSkillSessionId(uid, skillId);
+ const oldSid = defaultSkillSessionId(skillId);
try { evictSession(oldSid); } catch { /* not in cache */ }
const oldSessionJsonl = userSessionFile(uid, oldSid);
try { fs.unlinkSync(oldSessionJsonl); }
@@ -691,7 +701,7 @@ export async function deleteCustomSkill(skillId: string): Promise<boolean> {
catch (err) { log.warn(`rm failed user=${uid} skill=${skillId}: ${(err as Error).message}`); }
invalidateLineCount(path.join(chatDir, 'chat.jsonl'));
}
- const sessionId = defaultSkillSessionId(uid, skillId);
+ const sessionId = defaultSkillSessionId(skillId);
try { evictSession(sessionId); } catch { /* cache may not hold it */ }
const sessionJsonl = userSessionFile(uid, sessionId);
try { fs.unlinkSync(sessionJsonl); }
@@ -1013,8 +1023,8 @@ function skillChatMetaPath(userId: string, skillId: string): string {
return path.join(skillChatDir(userId, skillId), 'chat.json');
}
-function defaultSkillSessionId(userId: string, skillId: string): string {
- return `${userId}-skill-${skillId}`;
+function defaultSkillSessionId(skillId: string): string {
+ return `skill-${skillId}`;
}
async function loadSkillChatMeta(userId: string, skillId: string): Promise<SkillChatMeta> {
@@ -1051,7 +1061,7 @@ export async function clearSkillChat(userId: string, skillId: string): Promise<b
// even though the UI history is empty — visible as the LLM "remembering"
// pre-clear state, e.g. trying to read paths that no longer exist after a
// promote-to-builtin. Session id is id-keyed so it survives source changes.
- const sessionId = defaultSkillSessionId(userId, skillId);
+ const sessionId = defaultSkillSessionId(skillId);
try { evictSession(sessionId); } catch { /* not in cache */ }
try { await fsp.unlink(userSessionFile(userId, sessionId)); }
catch (err) {
@@ -1321,7 +1331,7 @@ export async function sendToSkillChat(userId: string, skillId: string, content:
if (!skill) return { ok: false, error: 'skill not found' };
const meta = await loadSkillChatMeta(userId, skillId);
- const sessionId = meta.session_id || defaultSkillSessionId(userId, skillId);
+ const sessionId = meta.session_id || defaultSkillSessionId(skillId);
const systemPrompt = await buildSkillEditSystemPrompt(skill);
@@ -1404,7 +1414,7 @@ export async function* streamSendToSkillChat(
}
const meta = await loadSkillChatMeta(userId, skillId);
- const sessionId = meta.session_id || defaultSkillSessionId(userId, skillId);
+ const sessionId = meta.session_id || defaultSkillSessionId(skillId);
const systemPrompt = await buildSkillEditSystemPrompt(skill);
diff --git a/src/main/features/users.ts b/src/main/features/users.ts
index 583ccd3b..30e34f71 100644
--- a/src/main/features/users.ts
+++ b/src/main/features/users.ts
@@ -190,6 +190,57 @@ export function activateUser(uid: string): void {
log.info(`active user_id=${uid}`);
}
+/**
+ * DEV CONVENIENCE — align the active local data uid with the account's server-side user_id, so a
+ * dev tester logging into a different account doesn't end up with a mismatched local data dir:
+ * - `data/<serverUid>/` already exists → switch the active uid to it (the old dir is left alone).
+ * - else, `data/<currentUid>/` exists → rename it to `data/<serverUid>/`, drop the stale registry
+ * entry, and re-activate.
+ * - else → just (re-)activate `<serverUid>`.
+ *
+ * **Callers MUST gate this on `!app.isPackaged`** — it is a dev-only behavior; it must not run in
+ * packaged builds. Returns true if it changed the active uid.
+ */
+export function reconcileDevUid(serverUid: string): boolean {
+ const target = String(serverUid || '').trim();
+ if (!target || !safeId(target)) {
+ log.warn(`reconcileDevUid: server uid not usable as a local uid, skipping: ${JSON.stringify(serverUid)}`);
+ return false;
+ }
+ // Server's `gen_uuid()` was changed to emit dashless 32-hex going forward (Server/utils/util.py),
+ // so the value here is already in the canonical local form — no client-side normalization
+ // needed. Accounts created before that change still carry the older `XXXXXXXX-XXXX-XXXX-…`
+ // shape on disk; safeId() accepts both, the equality check below is a literal compare, and
+ // path segments don't care about format.
+ const current = getActiveUserId();
+ if (target === current) return false;
+
+ const targetExists = fs.existsSync(userRoot(target));
+ const currentExists = fs.existsSync(userRoot(current));
+ try {
+ if (!targetExists && currentExists) {
+ fs.renameSync(userRoot(current), userRoot(target));
+ // Drop the stale `current` entry; activateUser() below adds `target` + flips current_user_id.
+ const reg = readRegistry();
+ if (reg) {
+ reg.users = reg.users.filter((u) => u.user_id !== current);
+ if (reg.current_user_id === current) reg.current_user_id = target;
+ writeRegistry(reg);
+ }
+ log.info(`reconcileDevUid: renamed local data dir ${current} -> ${target}`);
+ } else if (targetExists) {
+ log.info(`reconcileDevUid: switching active uid ${current} -> ${target} (target data dir already present)`);
+ } else {
+ log.info(`reconcileDevUid: no data dir to move; activating fresh ${target}`);
+ }
+ activateUser(target);
+ return true;
+ } catch (err) {
+ log.error(`reconcileDevUid ${current} -> ${target} failed: ${(err as Error).message}`);
+ return false;
+ }
+}
+
/**
* Boot-time entrypoint — read users.json and activate current_user_id; if
* none, generate a new uid and activate that. Returns the record.
diff --git a/src/main/ipc/connectors.ts b/src/main/ipc/connectors.ts
index e6db01e5..dbb98d0b 100644
--- a/src/main/ipc/connectors.ts
+++ b/src/main/ipc/connectors.ts
@@ -14,13 +14,29 @@
* the flow and waits for the deep-link callback.
*/
import * as connectors from '../features/connectors';
+import { isConnectorEnabled, setConnectorEnabled } from '../features/component_enabled';
export const invokeHandlers = {
'connectors.catalog': async () => ({ catalog: connectors.CONNECTOR_CATALOG }),
- 'connectors.list': async (_payload: unknown, ctx: { userId: string }) => ({
- instances: connectors.listInstances(ctx.userId),
- }),
+ 'connectors.list': async (_payload: unknown, ctx: { userId: string }) => {
+ // Attach the per-user `enabled` flag so the renderer can render the "停用 / 启用" toggle
+ // without a second IPC. Defaults to true when the user hasn't toggled it (the file only
+ // stores `false` overrides — see features/component_enabled.ts).
+ const raw = connectors.listInstances(ctx.userId);
+ const instances = raw.map((inst) => ({ ...inst, enabled: isConnectorEnabled(ctx.userId, inst.id) }));
+ return { instances };
+ },
+
+ 'connectors.set_enabled': async (
+ payload: { id?: unknown; enabled?: unknown },
+ ctx: { userId: string },
+ ) => {
+ if (typeof payload?.id !== 'string') throw new Error('invalid id');
+ if (typeof payload?.enabled !== 'boolean') throw new Error('invalid enabled flag');
+ setConnectorEnabled(ctx.userId, payload.id, payload.enabled);
+ return { ok: true, enabled: payload.enabled };
+ },
'connectors.start_oauth': async (payload: { catalog_id?: unknown }, ctx: { userId: string }) => {
if (typeof payload?.catalog_id !== 'string') throw new Error('invalid catalog_id');
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 71b7499b..38a43b2d 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -75,7 +75,7 @@ function buildSkillSandboxEnv(): Record<string, string> {
export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<StreamEvent, void, unknown> {
const {
userId, message,
- sessionId = `${userId}-anon-${genConversationId().slice(0, 8)}`,
+ sessionId = `anon-${genConversationId().slice(0, 8)}`,
systemPrompt,
workingDir,
images,
diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.ts
index 2aab6be9..5c331682 100644
--- a/src/main/model/core-agent/connector-meta-tools.ts
+++ b/src/main/model/core-agent/connector-meta-tools.ts
@@ -54,34 +54,24 @@ function errResult(code: string, msg: string): ToolResult {
return { content: `${code}: ${msg}`, isError: true };
}
-/** Status suffix appended to a connector line. Empty for the healthy `connected` case (most
- * connectors most of the time) — keeps each line short. Non-empty for states the model needs
- * to surface to the user. */
-function _statusSuffix(status: ConnectorInstance['status']): string {
- switch (status.kind) {
- case 'connected': return '';
- case 'connecting': return ' — connecting';
- case 'disconnected': return ' — disconnected (ask user to refresh)';
- case 'error': return ` — error: ${status.message}`;
- default: return ` — ${(status as { kind: string }).kind}`;
- }
-}
-
function _renderConnectorLine(instance: ConnectorInstance): string {
// Catalog entry holds the bilingual description; instance.id doubles as the catalog id (per
// types.ts: instance.id is the catalog entry id, used both for routing and as the
// `<id>__<tool>` prefix). Falls back to display_name alone when the catalog has no
// description (shouldn't happen for shipped connectors).
+ //
+ // No status suffix: `resolveVisibleConnectors` filters to `status.kind === 'connected'` so
+ // every line is implicitly healthy. Disconnected / errored / connecting instances are hidden
+ // from the LLM entirely — see tools-adapter.ts for the filter + rationale.
const catalog = findCatalogEntry(instance.id);
const lang = getCurrentLang();
const desc = catalog
? (lang === 'zh' ? catalog.description_zh : catalog.description_en)
: '';
const acct = instance.oauth_grant?.account_label ? ` (account: ${instance.oauth_grant.account_label})` : '';
- const head = desc
- ? `**${instance.id}** — ${instance.display_name}: ${desc}${acct}`
- : `**${instance.id}** — ${instance.display_name}${acct}`;
- return `- ${head}${_statusSuffix(instance.status)}`;
+ return desc
+ ? `- **${instance.id}** — ${instance.display_name}: ${desc}${acct}`
+ : `- **${instance.id}** — ${instance.display_name}${acct}`;
}
/** Render the `## Connectors` system-prompt block — pure enumeration (one line per connector).
@@ -128,16 +118,13 @@ function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {
const visible = await resolveVisibleConnectors(opts.userId, opts.agentId);
const match = visible.find((v) => v.instance.id === cid);
if (!match) {
+ // resolveVisibleConnectors already filters to `status.kind === 'connected'`, so a miss
+ // here means either the id is wrong OR the connector went disconnected between block
+ // render and this call. Either way the LLM's recovery is identical (re-read the
+ // `## Connectors` block, or ask the user to refresh) — one error code keeps it simple.
return errResult(
'E_CONNECTOR_NOT_VISIBLE',
- `connector "${cid}" is not enabled for this conversation. See the \`## Connectors\` system-prompt block for valid ids.`,
- );
- }
- if (match.instance.status.kind !== 'connected') {
- return errResult(
- 'E_CONNECTOR_NOT_CONNECTED',
- `connector "${cid}" is currently ${match.instance.status.kind}. ` +
- 'Tell the user to open the Connectors panel and click "刷新工具" / "Refresh tools".',
+ `connector "${cid}" is not currently available. See the \`## Connectors\` system-prompt block for valid ids; if it was there a moment ago, ask the user to refresh it in the Connectors panel.`,
);
}
if (!match.tools.length) {
@@ -261,13 +248,28 @@ function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {
};
}
-/** Build the connector meta-tools for a single runner. Returns `[]` when uid is empty OR when
- * the actor has no visible connectors — in that case the system prompt also doesn't carry the
- * `## Connectors` block, so the tools have nothing to act on and would only confuse the model. */
-export async function createConnectorMetaTools(opts: ConnectorMetaToolsOpts): Promise<AgentTool[]> {
+/** Build the connector meta-tools for a single runner.
+ *
+ * `mode` selects exposure (mirrors the tri-state gate in `runner.ts::connectorExposureFromSessionId`):
+ * - `'full'` → both `list_connector_tools` + `call_connector_tool` (gconv / gmember
+ * sessions — actual user tasks invoking external services).
+ * - `'discover'` → `list_connector_tools` only (agent-edit session — the editor LLM uses
+ * it to learn each connector's actions so the authored workflow can name
+ * specific action names like "gmail's `send_email`" instead of just
+ * "gmail's email-sending feature". `call_connector_tool` is withheld so an
+ * authoring session can never produce external side effects.).
+ *
+ * Returns `[]` when uid is empty OR when the actor has no visible connectors — in that case
+ * the system prompt also doesn't carry the `## Connectors` block, so the tools have nothing
+ * to act on and would only confuse the model. */
+export async function createConnectorMetaTools(
+ opts: ConnectorMetaToolsOpts,
+ mode: 'full' | 'discover' = 'full',
+): Promise<AgentTool[]> {
if (!opts.userId) return [];
const visible = await resolveVisibleConnectors(opts.userId, opts.agentId);
if (!visible.length) return [];
+ if (mode === 'discover') return [createListConnectorToolsTool(opts)];
return [
createListConnectorToolsTool(opts),
createCallConnectorToolTool(opts),
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index f25b283f..82414f24 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -170,10 +170,11 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// Per-user disabled-skill set; passed into getSystemPromptBlock so the
// rendered `## Available skills` block excludes user-disabled skills regardless
- // of agent-level allowlist. Resolved off the active uid (we don't have
- // params.userId yet for early auth-gate paths but session_id always carries
- // it). Falls back to empty set when uid can't be parsed (ad-hoc/test).
- const earlyUid = params.userId || extractUidFromSessionId(params.sessionId);
+ // of agent-level allowlist. Resolved off the active uid; session_id no longer
+ // carries the uid (CLAUDE.md §5), so callers that don't pass `params.userId`
+ // fall through to the active-user singleton. Wrapped in a try/catch so ad-hoc
+ // test paths that activate no user just see a null uid → empty disabled set.
+ const earlyUid = params.userId || _safeActiveUserId();
const disabledSkillIds = earlyUid ? readDisabledSets(earlyUid).skills : new Set<string>();
// System A render allowlist = intersect(skillList, project bindings).
@@ -198,6 +199,10 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// Build tools array: memory tool + metacognition tool.
const uid = params.userId || extractUidFromSessionId(params.sessionId);
+ // Build tools array: memory tool + metacognition tool. Assembly stays
+ // above the system-prompt build because finalToolNames is still snapshotted
+ // for the dev archive after this section.
+ const uid = params.userId || _safeActiveUserId();
const agentId = params.agentId || '';
const injectedTools: AgentTool[] = [];
@@ -298,27 +303,35 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// selection-accuracy cliff and invalidate the prompt-cache prefix on every connect/disconnect.
//
// Session-kind gate (tri-state):
- // - `gconv` (commander) + `gmember` (agent worker) → block + tools (full exposure)
- // - `agent` (agent-edit) → block only (LLM authoring the
- // workflow needs to know what
- // connectors exist so it can write
- // "use the notion connector" etc.,
- // but must NOT actually invoke them
- // from an authoring session)
+ // - `gconv` (commander) + `gmember` (agent worker) → block + full tools (list + call —
+ // actual user tasks invoking external
+ // services).
+ // - `agent` (agent-edit) → block + discover-only tool
+ // (`list_connector_tools`). Editor
+ // LLM reads action names + JSON
+ // schemas so the authored workflow
+ // can write "use gmail's `send_email`
+ // with body=..." rather than the
+ // coarse "use gmail to send email".
+ // `call_connector_tool` is withheld
+ // so an authoring session can never
+ // produce external side effects.
// - everything else (skill-edit / KB-image / CLI dispatch / reflect / memory-extract /
- // anon) → none (no accidental external side
- // effects from non-task sessions)
+ // anon) → none.
// For agent-edit specifically, the block intentionally bypasses `agent.enabled_connectors`
// (passes undefined agentId) — the editor LLM should see EVERYTHING the user installed so it
// can recommend referencing a connector even if the agent's whitelist hasn't been opened to
// it yet (the user toggles `enabled_connectors` separately in the agent-edit UI).
const exposure = uid ? connectorExposureFromSessionId(params.sessionId) : 'none';
- const blockAgentId = exposure === 'block-only' ? undefined : (agentId || undefined);
+ const blockAgentId = exposure === 'discover+block' ? undefined : (agentId || undefined);
const connectorBlock = exposure !== 'none' && uid
? await getConnectorPromptBlock(uid, blockAgentId)
: '';
- const connectorMetaTools = exposure === 'tools+block' && uid
- ? await createConnectorMetaTools({ userId: uid, ...(agentId ? { agentId } : {}) })
+ const connectorMetaTools = uid && exposure !== 'none'
+ ? await createConnectorMetaTools(
+ { userId: uid, ...(agentId ? { agentId } : {}) },
+ exposure === 'discover+block' ? 'discover' : 'full',
+ )
: [];
// Merge injected tools with extra tools from caller
@@ -483,42 +496,39 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
};
}
-/** Recognised session-kind keywords per CLAUDE.md §5. Order matters — longer alternatives must
- * come first so that e.g. `extract-img` matches as one kind, not as `extract` then leftover. */
-const _SESSION_KIND_RE = /-(gmember|gconv|memory-extract|extract-img|reflect|skill|agent|anon|cli)(?:-|$)/;
-
-/** Extract userId from session_id (`<uid>-<kind>-...` per CLAUDE.md §5). The uid may itself
- * contain dashes (UUID-shaped uids are real on this codebase: `D695-…-E3A9-gconv-…`), so we
- * can't just take the first dash-free segment. Instead we anchor on the kind keyword and
- * return everything before the leading `-` of that kind. Returns `null` when no recognised
- * kind is present (caller falls back to its own source of truth — typically `params.userId`). */
-export function extractUidFromSessionId(sessionId: string): string | null {
- const m = sessionId.match(_SESSION_KIND_RE);
- if (!m || m.index === undefined) return null;
- const uid = sessionId.slice(0, m.index);
- return uid || null;
+/** Best-effort accessor for the active uid that doesn't throw when no user is activated yet
+ * (ad-hoc / test paths). Production callers always come through with `params.userId` or after
+ * `activateUser()`, so the fallback is just a safety net. Loaded lazily via require to avoid
+ * pulling features/users into the early import graph. */
+function _safeActiveUserId(): string | null {
+ try {
+ const { getActiveUserId } = require('../../features/users') as typeof import('../../features/users');
+ return getActiveUserId();
+ } catch {
+ return null;
+ }
}
/** Tri-state connector exposure, gated by session kind (CLAUDE.md §5 session-id table):
- * - `tools+block`: group-chat sessions (`gconv` commander + `gmember` agent worker) — the
- * model both reads the catalog and invokes via the two meta-tools.
- * - `block-only`: agent-edit (`agent`) — the editor LLM sees the catalog so it can author a
- * workflow that references connectors by id, but the meta-tools are NOT injected (no
- * external side effects from an authoring session).
- * - `none`: skill-edit, KB-image, CLI dispatch, reflect, memory-extract, anon, and
+ * - `tools+block`: group-chat sessions (`gconv` commander + `gmember` agent worker) —
+ * block + both meta-tools (`list_connector_tools` + `call_connector_tool`). Full exposure.
+ * - `discover+block`: agent-edit (`agent`) — block + `list_connector_tools` ONLY. Editor LLM
+ * can discover action names + JSON schemas to write specific workflow steps; cannot invoke
+ * (an authoring session must never produce external side effects).
+ * - `none`: skill-edit, KB-image, CLI dispatch, reflect, memory-extract, anon, and
* any future kind — neither block nor tools.
- * Add a new conversation kind that needs connectors? Extend this gate explicitly + add an
- * entry to CLAUDE.md §5's session-id table.
+ * Add a new conversation kind that needs connectors? Extend this function explicitly + add
+ * an entry to CLAUDE.md §5's session-id table.
*
- * Implementation note: matches the kind keyword as a `-<kind>-` substring rather than anchoring
- * to the start. Real uids are sometimes UUID-shaped (`D695-…-E3A9`, multiple internal dashes),
- * so `^[^-]+-` would only ever capture the first hex group and miss every UUID-uid session.
- * Hex digits (`[0-9a-f]`) can't form `gconv` / `gmember` / `agent` (the `g`/`n`/`m`/`t`
- * characters disqualify them), and conv-ids / agent-ids in the tail use `[0-9a-f-]` — so the
- * substring search is collision-free. */
-export function connectorExposureFromSessionId(sessionId: string): 'tools+block' | 'block-only' | 'none' {
- if (/-(gconv|gmember)-/.test(sessionId)) return 'tools+block';
- if (/-agent-/.test(sessionId)) return 'block-only';
+ * session_id format is `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id), so the
+ * kind keyword is anchored at the start. */
+export function connectorExposureFromSessionId(sessionId: string): 'tools+block' | 'discover+block' | 'none' {
+ if (/^(gconv|gmember)-/.test(sessionId)) return 'tools+block';
+ // Agent-edit gets `list_connector_tools` (read-only, no side effects) so the editor LLM can
+ // learn each connector's action names and write specific workflow steps — but NOT
+ // `call_connector_tool`, since an authoring session must never produce external side
+ // effects. See `connector-meta-tools.ts::createConnectorMetaTools` mode handling.
+ if (/^agent-/.test(sessionId)) return 'discover+block';
return 'none';
}
diff --git a/src/main/model/core-agent/session-store.ts b/src/main/model/core-agent/session-store.ts
index 021d0006..bcba4708 100644
--- a/src/main/model/core-agent/session-store.ts
+++ b/src/main/model/core-agent/session-store.ts
@@ -1,7 +1,7 @@
/**
* Session store — maps a session_id (one per conversation) to a
* `PersistentSession` backed by a JSONL file under
- * `data/<user_id>/cloud/sessions/<session_id>.jsonl`.
+ * `data/<user_id>/{cloud,local}/sessions/<session_id>.jsonl`.
*
* session_id format (see CLAUDE.md §5):
* `<uid>-<kind>-<tail>`
@@ -18,6 +18,22 @@
* Legacy brand prefixes are stripped once at startup by the
* migration tool in features/users.ts and should not appear here;
* any id carrying such a prefix is treated as illegal.
+ * `<kind>-<tail>` — kind ∈ {gconv | gmember | skill | agent | extract-img |
+ * reflect | memory-extract | anon | cli}. The kind keyword is the FIRST
+ * segment, never an arbitrary prefix.
+ *
+ * user scoping comes from path root: `<activeUid>/{cloud,local}/sessions/<sid>.jsonl`
+ * resolved via `getActiveUserId()`. The session_id intentionally does NOT
+ * carry uid — repeating it in the filename added zero security (`sessionFileFor`
+ * was self-checking the prefix it just got handed) and forced uid to be
+ * dash-free, which broke when OAuth UUIDs entered the system.
+ *
+ * Builders (no uid param): features/group_chat/state.ts::{buildGconv,buildGmember}SessionId,
+ * features/agents.ts::defaultAgentEditSessionId, features/skills.ts::defaultSkillSessionId.
+ *
+ * Legacy formats (`aiteam-…` brand prefix, `<uid>-<kind>-<tail>` uid prefix) are
+ * stripped once at startup by `util/migrate-session-ids.ts` and should not appear
+ * here at runtime.
*
* session jsonl only carries the LLM-facing view (including tool_use /
* tool_result / compaction); it's a separate file from
@@ -49,14 +65,15 @@ const log = createLogger('model');
*/
const EPHEMERAL_KINDS = ['extract-img', 'reflect', 'memory-extract', 'anon'] as const;
-export function isEphemeralSessionId(userId: string, sessionId: string): boolean {
- // Caller is responsible for having validated the uid prefix. Tail can be
- // multi-segment (memory-extract / extract-img), so we can't split on '-' —
- // match against each known kind followed by '-' (or kind alone for edge
- // tests).
- const tail = sessionId.slice(userId.length + 1);
+/** All recognised kind keywords (used by `resolveSessionPath`'s kind-anchor assertion).
+ * Order matters in the regex alternation: longer alternatives must come before their
+ * shorter prefix overlaps so that e.g. `extract-img-…` matches as one kind, not as
+ * `extract` + leftover. */
+const KNOWN_KINDS_RE = /^(gmember|gconv|memory-extract|extract-img|reflect|skill|agent|anon|cli)(?:-|$)/;
+
+export function isEphemeralSessionId(sessionId: string): boolean {
for (const kind of EPHEMERAL_KINDS) {
- if (tail === kind || tail.startsWith(`${kind}-`)) return true;
+ if (sessionId === kind || sessionId.startsWith(`${kind}-`)) return true;
}
return false;
}
@@ -65,25 +82,25 @@ export function isEphemeralSessionId(userId: string, sessionId: string): boolean
* Build the filesystem path that backs a given session id, picking cloud or
* local based on the kind (see EPHEMERAL_KINDS above).
*
- * Assertion: `sessionId` must start with `<userId>-`. This blocks the legacy
- * format `<kind>-<uid>-<tail>` (used by extract/organizer before the rewrite)
- * from silently routing user-private jsonl into a wrong tree.
+ * Defensive assertion: `sessionId` must start with a known kind keyword.
+ * Catches accidental hand-built ids that don't go through a builder; without
+ * this guard a malformed id would just silently land at a wrong-shaped jsonl
+ * filename. user scoping itself is enforced by the caller passing `userId`
+ * (`sessionFileFor` reads it from `getActiveUserId()`); the session_id no
+ * longer carries it.
*
* Constructors (chats / group_chat / agents-edit / skills-edit / kb image
- * extract / reflection) must build ids via the feature-layer helpers; never
- * by hand.
+ * extract / reflection / cli) must build ids via the feature-layer helpers;
+ * never by hand.
*/
export function resolveSessionPath(userId: string, sessionId: string): string {
- const prefix = `${userId}-`;
- if (!sessionId.startsWith(prefix)) {
+ if (!KNOWN_KINDS_RE.test(sessionId)) {
throw new Error(
- `invalid session id "${sessionId}" — must start with "${prefix}" (user is ${userId})`,
+ `invalid session id "${sessionId}" — must start with a known kind ` +
+ `(gconv | gmember | skill | agent | extract-img | reflect | memory-extract | anon | cli)`,
);
}
- if (sessionId.length <= prefix.length) {
- throw new Error(`invalid session id "${sessionId}" — missing kind/tail after uid`);
- }
- return isEphemeralSessionId(userId, sessionId)
+ return isEphemeralSessionId(sessionId)
? userLocalSessionFile(userId, sessionId)
: userSessionFile(userId, sessionId);
}
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 12f6638b..c34f43b9 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -225,6 +225,14 @@ export const userComponentEnabledFile = (uid: string) => path.join(userCloudConf
// Same dir + cloud-sync policy as preferences.json; user-orchestration
// config, NOT per-agent runtime asset (those live under agents/<aid>/).
export const userScheduledTasksFile = (uid: string) => path.join(userCloudConfigDir(uid), 'scheduled_tasks.json');
+// Connector registry: installed MCP server instances + cached tool schemas + OAuth grants
+// (vault-encrypted with the active Orkas account's OAuth user_id as seed — see
+// `features/connectors/registry.ts`). Cloud-synced as of 2026-05-15 so a user authorizing on
+// one device sees the same connectors on another. **Vault key:** OAuth user_id (not local uid)
+// so any device logged into the same Orkas account can decrypt; OrkasOpen / not-logged-in
+// users fall back to local uid (the file then sits in cloud/config/ but doesn't actually
+// sync — sync engine is inactive without an account).
+export const userConnectorsConfigFile = (uid: string) => path.join(userCloudConfigDir(uid), 'connectors.json');
// ── Local-only per-user (never synced) ───────────────────────────────────
@@ -236,12 +244,6 @@ export const userAuthProfilesFile = (uid: string) => path.join(userLocalConfigDi
export const userWebSearchCache = (uid: string) => path.join(userLocalConfigDir(uid), 'web-search-cache.json');
export const userReflectionStateFile = (uid: string) => path.join(userLocalConfigDir(uid), 'reflection-state.json');
export const userDevtoolsFile = (uid: string) => path.join(userLocalConfigDir(uid), 'devtools.json');
-// Connector registry: installed MCP server instances + cached tool schemas.
-// Why under local/ rather than cloud/: holds access tokens (PATs / OAuth
-// bearers) and is machine-private by design; failure mode for sync would be
-// a token leaked to another device. Token-vault concerns: see
-// `features/connectors/registry.ts` header.
-export const userConnectorsConfigFile = (uid: string) => path.join(userLocalConfigDir(uid), 'connectors.json');
// Local search index (derived data, self-healing via reconcile, never synced).
// Only the main conversation + knowledge base get a persistent inverted
diff --git a/src/main/preload.js b/src/main/preload.js
index 2235b318..10814e65 100644
--- a/src/main/preload.js
+++ b/src/main/preload.js
@@ -124,58 +124,9 @@ function stream(channel, payload, onEvent) {
return { promise, cancel };
}
-// push channel are stripped from the OrkasOpen build — see OpenSource/SyncCode/strip-rules.json.
-const account = {
- status: () => invoke('account.status'),
- listProviders: () => invoke('account.listProviders'),
- startLogin: () => invoke('account.startLogin'),
- logout: () => invoke('account.logout'),
- currentUser: () => invoke('account.currentUser'),
- // Subscribe to status-change pushes from main (login completed / session revoked). Returns an
- // unsubscribe function.
- onChange: (cb) => {
- if (typeof cb !== 'function') return () => {};
- const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* renderer cb threw */ } };
- },
-};
-
-// Voice-to-text (the chat-composer mic button → the Server's /voice/asr_ws ASR proxy). The
-// `voice` namespace + renderer/modules/voice-input.js are stripped from the OrkasOpen build
-// (offline client, no Server) — see OpenSource/SyncCode/strip-rules.json.
-const voice = {
-};
-
-// Multi-device sync. Stripped from the OrkasOpen build along with the account namespace
-// it depends on — see OpenSource/SyncCode/strip-rules.json.
-const sync = {
- runNow: () => invoke('sync.runNow'),
- status: () => invoke('sync.status'),
- usage: () => invoke('sync.usage'),
- getEnabled: () => invoke('sync.getEnabled'),
- setEnabled: (enabled, opts) => invoke('sync.setEnabled', {
- enabled: !!enabled,
- purge: !!(opts && opts.purge),
- }),
- usageBreakdown: () => invoke('sync.usageBreakdown'),
- getPendingMassDelete: () => invoke('sync.getPendingMassDelete'),
- confirmPendingDelete: () => invoke('sync.confirmPendingDelete'),
- cancelPendingDelete: () => invoke('sync.cancelPendingDelete'),
- onStatus: (cb) => {
- if (typeof cb !== 'function') return () => {};
- const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* swallow */ } };
- },
- onUsage: (cb) => {
- if (typeof cb !== 'function') return () => {};
- const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* swallow */ } };
- },
- // Fires after a sync pass pulls / renames / tombstone-deletes at least one
- // file — the on-disk cloud/ tree now has content the renderer's in-memory
- // lists don't know about. Payload: { domains: string[], cids: string[] }.
- onDataChanged: (cb) => {
- if (typeof cb !== 'function') return () => {};
- const listener = (_evt, payload) => { try { cb(payload); } catch (_) { /* swallow */ } };
- },
-};
+// User-account login, voice ASR proxy, and multi-device sync namespaces are stripped from the
+// OrkasOpen build — see OpenSource/SyncCode/strip-rules.json. The renderer is not allowed to
+// reference these surfaces; renderer modules that depend on them are removed at sync time.
// Expose the sync-fetched i18n bundle on its own bridge key so the renderer
// can pick it up at module load. Read-only — the renderer never mutates it.
@@ -188,9 +139,6 @@ contextBridge.exposeInMainWorld('orkas', {
getLanguage: () => invoke('config.getLanguage'),
setLanguage: (language) => invoke('config.setLanguage', { language }),
getLocales: () => invoke('config.getLocales'),
- account,
- voice,
- sync,
invoke,
stream,
onPushEvent,
diff --git a/src/main/prompts/chat_agent_setup.md b/src/main/prompts/chat_agent_setup.md
index 0c3e65bc..f1dd6e76 100644
--- a/src/main/prompts/chat_agent_setup.md
+++ b/src/main/prompts/chat_agent_setup.md
@@ -29,7 +29,7 @@ This is the per-agent inline edit chat — the agent you're refining is identifi
3. **Tool / skill priority** when authoring workflow actions (per agent-creator rules):
- **Built-in tools** (file IO, `bash`, `kb_search`, `kb_read`, `markdown_to_pdf`, `html_to_pdf`, `generate_image`, `web_search`, `web_fetch`) — write the tool name directly. **No skill wrapper needed** for single-step actions.
- **Then check the "Available skills" section** — skills are most useful for: multi-step logic encapsulation, third-party paid APIs (with credential management), recurrent compound flows. If one fits, use it; don't reinvent the wheel.
- - **Connectors**: when the system prompt has a `## Connectors` block, you may reference any listed connector by id in the workflow (e.g. "use the `notion` connector to create a page"). The block lists every connector the user has installed, regardless of this agent's current allowed-list — if you reference one the user hasn't allowed for this agent, they'll need to enable it in the agent-edit UI's "Allowed connectors" section before the agent can call it. You don't author the allowed-list yourself (UI-only field). The actual invocation tools aren't available in this editing session by design.
+ - **Connectors**: when the system prompt has a `## Connectors` block, you may reference any listed connector by id in the workflow. Use `list_connector_tools({connector_id})` to see the connector's available actions + JSON input schemas — then write **specific** workflow steps naming the action (e.g. "use `gmail`'s `send_email` action with subject/body from step 2") rather than vague references ("use gmail to send email"). The block lists every connector the user has installed regardless of this agent's current allowed-list; if you reference one not yet allowed for this agent, they'll need to enable it in the agent-edit UI's "Allowed connectors" section before the agent can call it. You do NOT author the allowed-list yourself (UI-only field). `call_connector_tool` is NOT available in this editing session by design — you discover schemas but never execute, so authoring produces no external side effects.
- **Only when none of the above has it**, tell the user "we need a skill called X to do Y" — this is a fallback, not the default. An agent that uses no skills at all is a perfectly common, legal shape.
- **Web access**: this system auto-picks the best of "vendor-native search → search-type skill → built-in `web_search`+`web_fetch`" in three tiers; in workflow just write "use `web_search`" — at runtime it upgrades per available capability. Don't write degradation branches.
4. **On failure, state the cause clearly + suggest a remedy**; do not power through.
diff --git a/src/main/util/crypto-vault.ts b/src/main/util/crypto-vault.ts
index d52314b9..b845d0b8 100644
--- a/src/main/util/crypto-vault.ts
+++ b/src/main/util/crypto-vault.ts
@@ -42,10 +42,14 @@ const APP_SALT = Buffer.from('orkas/connectors/v1', 'utf8');
const _keyCache = new Map<string, Buffer>();
-function _deriveKey(uid: string): Buffer {
- if (_keyCache.has(uid)) return _keyCache.get(uid)!;
- const k = crypto.pbkdf2Sync(uid, APP_SALT, ITER, KEY_LEN, 'sha256');
- _keyCache.set(uid, k);
+// The seed is any opaque string the caller controls — historically the local uid (machine-
+// private encryption), now also the Orkas-account OAuth user_id when the file is meant to be
+// decrypted cross-device after cloud sync (see `features/connectors/registry.ts` for that
+// case). The function doesn't care which it is; the caller picks.
+function _deriveKey(seed: string): Buffer {
+ if (_keyCache.has(seed)) return _keyCache.get(seed)!;
+ const k = crypto.pbkdf2Sync(seed, APP_SALT, ITER, KEY_LEN, 'sha256');
+ _keyCache.set(seed, k);
return k;
}
@@ -61,9 +65,9 @@ export function isEncryptedPayload(text: string): boolean {
}
}
-export function encrypt(uid: string, plaintext: string): string {
- if (!uid) throw new Error('crypto-vault: uid required');
- const key = _deriveKey(uid);
+export function encrypt(seed: string, plaintext: string): string {
+ if (!seed) throw new Error('crypto-vault: seed required');
+ const key = _deriveKey(seed);
const iv = crypto.randomBytes(IV_LEN);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
@@ -72,15 +76,15 @@ export function encrypt(uid: string, plaintext: string): string {
return blob.toString('base64');
}
-export function decrypt(uid: string, b64: string): string {
- if (!uid) throw new Error('crypto-vault: uid required');
+export function decrypt(seed: string, b64: string): string {
+ if (!seed) throw new Error('crypto-vault: seed required');
const blob = Buffer.from(b64, 'base64');
if (blob.length < MAGIC.length + IV_LEN + TAG_LEN) throw new Error('crypto-vault: payload too short');
if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error('crypto-vault: bad magic');
const iv = blob.subarray(MAGIC.length, MAGIC.length + IV_LEN);
const tag = blob.subarray(MAGIC.length + IV_LEN, MAGIC.length + IV_LEN + TAG_LEN);
const ct = blob.subarray(MAGIC.length + IV_LEN + TAG_LEN);
- const key = _deriveKey(uid);
+ const key = _deriveKey(seed);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8');
diff --git a/src/main/util/migrate-connectors-to-cloud.ts b/src/main/util/migrate-connectors-to-cloud.ts
new file mode 100644
index 00000000..a805079c
--- /dev/null
+++ b/src/main/util/migrate-connectors-to-cloud.ts
@@ -0,0 +1,100 @@
+/**
+ * One-shot migration: relocate the connectors registry from `<uid>/local/config/connectors.json`
+ * to `<uid>/cloud/config/connectors.json` and re-key the vault from local-uid encryption to
+ * OAuth user_id encryption (so any device signed into the same Orkas account can decrypt).
+ *
+ * Called from `index.ts` after `account.bootstrap()` resolves to `ready`. Idempotent — second
+ * runs detect the cloud file exists and bail. Migration is **bound to login**: without an
+ * OAuth user_id we'd be re-encrypting with the same local-uid seed for no benefit (and the
+ * cloud copy wouldn't sync anyway because the engine is inactive without an account), so we
+ * defer to a future login.
+ *
+ * Failure modes:
+ * - decrypt of old file fails → leave the local file alone, log, return false. User
+ * reconnects when they hit a connector card.
+ * - write of new file fails → leave both, the next launch retries.
+ * - both succeed → unlink the old file. The cloud file is now authoritative.
+ *
+ * The strip-rules-aware lazy-require for `features/account` lets this file ship to OrkasOpen
+ * unchanged; OrkasOpen has no account module → `oauthUserId()` resolves null → migration
+ * skips. That matches the no-login fallback behavior baked into registry.ts.
+ */
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+import { userCloudConfigDir, userLocalConfigDir } from '../paths';
+import { createLogger } from '../logger';
+import * as cryptoVault from './crypto-vault';
+
+const log = createLogger('migrate-connectors');
+
+const OLD_FILENAME = 'connectors.json';
+const NEW_FILENAME = 'connectors.json';
+const STAMP_FILE = '.migrate-connectors-to-cloud.done';
+
+function _oauthUserId(): string | null {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require
+ const account = require('../features/account') as { oauthUserId?: () => string | null };
+ return account.oauthUserId?.() ?? null;
+ } catch {
+ return null;
+ }
+}
+
+export function migrateConnectorsToCloud(uid: string): boolean {
+ if (!uid) return false;
+ const localDir = userLocalConfigDir(uid);
+ const cloudDir = userCloudConfigDir(uid);
+ const oldPath = path.join(localDir, OLD_FILENAME);
+ const newPath = path.join(cloudDir, NEW_FILENAME);
+ const stamp = path.join(cloudDir, STAMP_FILE);
+
+ // Already done — stamp file is the cheap idempotency check.
+ if (fs.existsSync(stamp)) return false;
+ // Cloud file already exists but no stamp → still drop the stamp so we don't re-evaluate
+ // every launch. (Fresh install or a manual cloud-side push from another device.)
+ if (fs.existsSync(newPath)) {
+ try { fs.mkdirSync(cloudDir, { recursive: true }); fs.writeFileSync(stamp, ''); } catch { /* ok */ }
+ return false;
+ }
+ // Nothing to migrate.
+ if (!fs.existsSync(oldPath)) {
+ try { fs.mkdirSync(cloudDir, { recursive: true }); fs.writeFileSync(stamp, ''); } catch { /* ok */ }
+ return false;
+ }
+
+ const oauth = _oauthUserId();
+ if (!oauth) {
+ // Defer until login. Don't drop the stamp — we WANT to retry on next launch.
+ log.info('connectors.json migration deferred — no OAuth user_id yet (login required)');
+ return false;
+ }
+
+ let plain: string;
+ try {
+ const raw = fs.readFileSync(oldPath, 'utf8');
+ plain = cryptoVault.isEncryptedPayload(raw) ? cryptoVault.decrypt(uid, raw) : raw;
+ } catch (err) {
+ log.error(`migrate decrypt failed: ${(err as Error).message} — leaving local file in place`);
+ return false;
+ }
+ try {
+ fs.mkdirSync(cloudDir, { recursive: true });
+ const enc = cryptoVault.encrypt(oauth, plain);
+ fs.writeFileSync(newPath, enc, { mode: 0o600 });
+ } catch (err) {
+ log.error(`migrate write failed: ${(err as Error).message}`);
+ return false;
+ }
+ try {
+ fs.unlinkSync(oldPath);
+ } catch (err) {
+ // Cloud file written, but old left — non-fatal. The cloud file is authoritative; the
+ // stale local file becomes unreachable garbage. Surface to log + continue.
+ log.warn(`migrate cleanup (unlink old) failed: ${(err as Error).message}`);
+ }
+ try { fs.writeFileSync(stamp, ''); } catch { /* ok */ }
+ log.info('connectors.json migrated to cloud + re-keyed to OAuth user_id');
+ return true;
+}
diff --git a/src/main/util/migrate-session-ids.ts b/src/main/util/migrate-session-ids.ts
index 08aeb0c6..3adffdfe 100644
--- a/src/main/util/migrate-session-ids.ts
+++ b/src/main/util/migrate-session-ids.ts
@@ -22,18 +22,59 @@
* sessions also get the prefix stripped. Their jsonl content is still
* valid (users can open old group-chat history); new code just no
* longer generates those kinds.
+ * One-shot data migration: strip any prefix segments before the kind keyword from session_id —
+ * both in jsonl filenames AND in stored references inside `_index.json` / `chat.json` —
+ * normalising every shape to `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id).
+ *
+ * Why touch the index files too: `cloud/chats/_index.json` and per-agent / per-skill
+ * `chat.json` persist the conversation's session_id. Renaming jsonl files alone is not enough;
+ * the next time the user opens an old conversation, `chats.ts` reads `conv.session_id` from
+ * the index, hands it to session-store, and a fresh dashed-name jsonl gets created — the rename
+ * undoes itself within minutes. The migration must rewrite these stored references too.
+ *
+ * Handles every legacy shape we've ever shipped:
+ * - `aiteam-gconv-cv1` (brand prefix from the v0 codename)
+ * - `orkas-gconv-cv1` (brand prefix from the rename)
+ * - `99999999-gconv-cv1` (8-digit numeric uid prefix)
+ * - `D69594E0-CF31-…-E3A9-gconv-cv1` (UUID uid prefix; OAuth user_id form)
+ * - `aiteam-99999999-gconv-cv1` (double prefix — brand + uid)
+ * All collapse to `gconv-cv1`. Files / fields already in `<kind>-…` form are left untouched.
+ *
+ * Same-name conflicts during file rename are log.warn'd and the source file is preserved.
+ * `<uid>/local/.migrations` is stamped with `MIGRATION_TAG` so the rename never reruns.
+ *
+ * Scan covers `<uid>/cloud/sessions/`, `<uid>/local/sessions/`, `cloud/chats/_index.json`,
+ * `cloud/chats/agent/<aid>/chat.json`, and `cloud/chats/skill/<sid>/chat.json`.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
-import { userSessionsDir, userLocalConfigDir } from '../paths';
+import {
+ userSessionsDir,
+ userLocalSessionsDir,
+ userLocalConfigDir,
+ userChatsDir,
+} from '../paths';
import { createLogger } from '../logger';
const log = createLogger('migrate');
-const MIGRATION_TAG = 'decouple-session-id-from-brand-v1';
-const LEGACY_PREFIX_RE = /^(aiteam|orkas)-/;
+// v2 (bumped from v1) re-runs the migration on machines already stamped, picking up two new
+// fixes: (a) chats/_index.json + chat/{agent,skill}/<id>/chat.json session_id fields are
+// rewritten so the next conv-open doesn't recreate the dashed jsonl; (b) the file rename
+// scan also covers local/sessions/ (was cloud-only in v1).
+const MIGRATION_TAG = 'drop-session-id-uid-prefix-v2';
+
+/** Strip any prefix segments BEFORE a known kind keyword. The lookahead anchors on the kind +
+ * the boundary that follows it (`-` for kinds-with-tail, `$` for kinds-without-tail like
+ * `anon` standalone). The lazy `.+?-` matches the smallest prefix that lets the lookahead
+ * succeed. Order in the alternation: longest first so `extract-img` matches whole, not as
+ * `extract` + leftover. */
+const FILENAME_PREFIX_RE =
+ /^.+?-(?=(?:gmember|gconv|memory-extract|extract-img|reflect|skill|agent|anon|cli|sub|organizer|conv)(?:-|\.jsonl$))/;
+const SID_PREFIX_RE =
+ /^.+?-(?=(?:gmember|gconv|memory-extract|extract-img|reflect|skill|agent|anon|cli|sub|organizer|conv)(?:-|$))/;
function migrationsFile(uid: string): string {
// userLocalConfigDir = <uid>/local/config; up one to <uid>/local/
@@ -62,44 +103,32 @@ interface MigrationStats {
renamed: number;
alreadyMigrated: number;
conflicts: number;
+ /** Number of session_id fields rewritten across all index / chat.json files. */
+ fieldsRewritten: number;
}
-/**
- * Run the migration for one uid. Idempotent: a previously-stamped uid is a
- * no-op. Safe to call on every boot.
- */
-export function migrateLegacySessionIds(uid: string): MigrationStats {
- const stats: MigrationStats = { scanned: 0, renamed: 0, alreadyMigrated: 0, conflicts: 0 };
- if (alreadyApplied(uid)) {
- return stats;
- }
-
- const dir = userSessionsDir(uid);
- if (!fs.existsSync(dir)) {
- stamp(uid);
- return stats;
- }
-
- let entries: string[] = [];
+function migrateOneDir(dir: string, stats: MigrationStats): void {
+ if (!fs.existsSync(dir)) return;
+ let entries: string[];
try {
entries = fs.readdirSync(dir);
} catch (err) {
log.warn(`readdir failed ${dir}: ${(err as Error).message}`);
- return stats;
+ return;
}
-
for (const name of entries) {
if (!name.endsWith('.jsonl')) continue;
stats.scanned += 1;
- if (!LEGACY_PREFIX_RE.test(name)) {
+ const newName = name.replace(FILENAME_PREFIX_RE, '');
+ if (newName === name) {
+ // Already in `<kind>-<tail>.jsonl` form — no prefix to strip.
stats.alreadyMigrated += 1;
continue;
}
- const newName = name.replace(LEGACY_PREFIX_RE, '');
const src = path.join(dir, name);
const dst = path.join(dir, newName);
if (fs.existsSync(dst)) {
- log.warn(`migration conflict: ${newName} already exists, skipping ${name}`);
+ log.warn(`migration conflict: ${newName} already exists at ${dir}, preserving ${name} for triage`);
stats.conflicts += 1;
continue;
}
@@ -110,11 +139,107 @@ export function migrateLegacySessionIds(uid: string): MigrationStats {
log.warn(`rename failed ${src} → ${dst}: ${(err as Error).message}`);
}
}
+}
+
+/** Strip any uid/brand prefix from a session_id string. Returns the input unchanged when no
+ * prefix is present. */
+function _stripSidPrefix(sid: unknown): { sid: string; changed: boolean } | null {
+ if (typeof sid !== 'string' || !sid) return null;
+ const stripped = sid.replace(SID_PREFIX_RE, '');
+ return { sid: stripped, changed: stripped !== sid };
+}
+
+/** Rewrite session_id fields inside `cloud/chats/_index.json` (array of conv records). */
+function migrateChatsIndex(uid: string, stats: MigrationStats): void {
+ const file = path.join(userChatsDir(uid), '_index.json');
+ if (!fs.existsSync(file)) return;
+ let raw: string;
+ try { raw = fs.readFileSync(file, 'utf8'); }
+ catch (err) { log.warn(`read _index.json: ${(err as Error).message}`); return; }
+ let parsed: unknown;
+ try { parsed = JSON.parse(raw); }
+ catch (err) { log.warn(`parse _index.json: ${(err as Error).message}`); return; }
+ if (!Array.isArray(parsed)) return;
+ let touched = 0;
+ for (const row of parsed) {
+ if (!row || typeof row !== 'object') continue;
+ const r = row as Record<string, unknown>;
+ const result = _stripSidPrefix(r.session_id);
+ if (result?.changed) {
+ r.session_id = result.sid;
+ touched += 1;
+ }
+ }
+ if (touched === 0) return;
+ try {
+ fs.writeFileSync(file, JSON.stringify(parsed, null, 2), 'utf8');
+ stats.fieldsRewritten += touched;
+ } catch (err) {
+ log.warn(`write _index.json: ${(err as Error).message}`);
+ }
+}
+
+/** Rewrite session_id field inside a `chat.json` (per-agent or per-skill edit chat meta). */
+function migrateChatMeta(file: string, stats: MigrationStats): void {
+ if (!fs.existsSync(file)) return;
+ let raw: string;
+ try { raw = fs.readFileSync(file, 'utf8'); }
+ catch (err) { log.warn(`read ${file}: ${(err as Error).message}`); return; }
+ let parsed: unknown;
+ try { parsed = JSON.parse(raw); }
+ catch (err) { log.warn(`parse ${file}: ${(err as Error).message}`); return; }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return;
+ const obj = parsed as Record<string, unknown>;
+ const result = _stripSidPrefix(obj.session_id);
+ if (!result?.changed) return;
+ obj.session_id = result.sid;
+ try {
+ fs.writeFileSync(file, JSON.stringify(parsed, null, 2), 'utf8');
+ stats.fieldsRewritten += 1;
+ } catch (err) {
+ log.warn(`write ${file}: ${(err as Error).message}`);
+ }
+}
+
+/** Walk `cloud/chats/{agent,skill}/<id>/chat.json` and rewrite the session_id field in each. */
+function migrateAgentSkillChatMetas(uid: string, stats: MigrationStats): void {
+ const chatsRoot = userChatsDir(uid);
+ for (const sub of ['agent', 'skill']) {
+ const root = path.join(chatsRoot, sub);
+ if (!fs.existsSync(root)) continue;
+ let entries: string[];
+ try { entries = fs.readdirSync(root); }
+ catch (err) { log.warn(`readdir ${root}: ${(err as Error).message}`); continue; }
+ for (const id of entries) {
+ const meta = path.join(root, id, 'chat.json');
+ migrateChatMeta(meta, stats);
+ }
+ }
+}
+
+/**
+ * Run the migration for one uid. Idempotent: a previously-stamped uid is a no-op. Safe to
+ * call on every boot (invoked by `features/users.activateUser`).
+ */
+export function migrateLegacySessionIds(uid: string): MigrationStats {
+ const stats: MigrationStats = { scanned: 0, renamed: 0, alreadyMigrated: 0, conflicts: 0, fieldsRewritten: 0 };
+ if (alreadyApplied(uid)) {
+ return stats;
+ }
+
+ // Files first — rename jsonls before we touch the indexes that reference them.
+ migrateOneDir(userSessionsDir(uid), stats);
+ migrateOneDir(userLocalSessionsDir(uid), stats);
+ // Then rewrite the stored session_id references so reads don't reanimate the old shape.
+ migrateChatsIndex(uid, stats);
+ migrateAgentSkillChatMetas(uid, stats);
stamp(uid);
- if (stats.renamed || stats.conflicts) {
+ if (stats.renamed || stats.conflicts || stats.fieldsRewritten) {
log.info(
- `session id migration done uid=${uid} renamed=${stats.renamed} conflicts=${stats.conflicts} alreadyMigrated=${stats.alreadyMigrated}`,
+ `session id migration done uid=${uid} renamed=${stats.renamed} ` +
+ `fieldsRewritten=${stats.fieldsRewritten} conflicts=${stats.conflicts} ` +
+ `alreadyMigrated=${stats.alreadyMigrated}`,
);
}
return stats;
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 11c7115e..e1f8a44f 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -541,6 +541,21 @@
</div>
</div>
</div>
+
+ <!-- Subscription / membership card — populated by views/login/account_settings.js
+ alongside the Account card. Hidden when not signed in (matches the Account card's
+ visibility). Stripped from the OrkasOpen build with the rest of the account block.
+ Layout: badge chip inline with status text (no avatar circle — that visual slot is
+ for user identity, not tier marker). -->
+ <div class="settings-group-head">
+ <div class="settings-group-title" data-i18n="account.subscription_title">会员</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <!-- Past-due / grace warning row, populated only when status warrants. -->
+ </div>
+ </div>
</div>
<!-- ───────────────────────── 数据 ───────────────────────── -->
@@ -554,10 +569,19 @@
<!-- Card 1: 主开关 + 状态 + 立即同步 -->
<div class="settings-group-head">
- <div class="settings-group-title" data-i18n="settings.sync.title">云端同步</div>
+ <div class="settings-group-title">
+ <span data-i18n="settings.sync.title">云端同步</span>
+ </div>
<div class="settings-group-sub" data-i18n="settings.sync.privacy_note">数据通过 HTTPS 加密上传到私有云存储,仅你的账号可访问。</div>
</div>
- <div class="settings-row">
+ <!-- Pro-required row: shown when current user is not Pro.
+ Replaces the toggle row in that state so the user gets a
+ clear "this is a Pro feature, subscribe" affordance instead
+ of a toggle that just bounces them to a dialog. The
+ existing toggle row + controls row still exist and stay
+ functional for Pro users. -->
+ <span class="settings-status" data-i18n="settings.sync.pro_required">云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。</span>
+ </div>
<label class="settings-toggle settings-toggle-tight">
<span data-i18n="settings.sync.toggle_enable">启用云端同步</span>
</label>
@@ -1004,6 +1028,13 @@
<script src="./modules/i18n.js"></script>
<script src="./modules/model-guard.js"></script>
<script src="./modules/boot.js"></script>
+ <!-- Account login gate + Settings account card — stripped in OrkasOpen. login_panel.js must load
+ after boot.js (it calls bootApp); account_settings.js is invoked from settings.js::loadSettings. -->
+ <script src="./views/login/login_panel.js"></script>
+ <script src="./views/login/account_settings.js"></script>
+ <!-- Pro entitlement gate (renderer-side). Loads before voice / sync so window.proGate
+ exists when those modules attach button handlers. Stripped in OrkasOpen. -->
+ <script src="./modules/pro_gate.js"></script>
<script src="./modules/avatar.js"></script>
<script src="./modules/avatar-picker.js"></script>
<script src="./modules/chat-input-form.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 475ea734..d6d79ea0 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -1,4 +1,49 @@
{
+ "account.gate_title": "Sign in to Orkas",
+ "account.gate_signin": "Sign in",
+ "account.gate_signin_pending": "Opening sign-in page…",
+ "account.gate_signin_again": "Reopen sign-in page",
+ "account.gate_signing_in": "Signing in…",
+ "account.gate_browser_hint": "Opened the sign-in page in your browser; you'll be brought back automatically.",
+ "account.gate_sub": "Sign in to your account to continue",
+ "account.gate_hint": "Authorize in the browser that opens; you'll be brought back automatically",
+ "account.provider_google": "Continue with Google",
+ "account.provider_apple": "Continue with Apple",
+ "account.provider_generic": "Continue with {provider}",
+ "account.error_start": "Couldn't start sign-in. Please try again.",
+ "account.error_cancelled": "Authorization cancelled",
+ "account.error_generic": "Sign-in failed",
+ "account.settings_title": "Account",
+ "account.settings_logout": "Sign out",
+ "account.settings_signed_in": "Signed in",
+ "account.subscription_title": "Subscription",
+ "account.subscription_status_active": "Renews",
+ "account.subscription_status_will_cancel": "Cancels",
+ "account.subscription_status_past_due": "Payment issue",
+ "account.subscription_status_expired": "Subscription ended",
+ "account.subscription_status_free": "Free plan",
+ "account.subscription_status_coming_soon": "Pro coming soon",
+ "account.subscription_detail_active": "Cloud sync and voice input are unlocked.",
+ "account.subscription_detail_will_cancel": "You keep Pro until the end of the period; then revert to Free.",
+ "account.subscription_detail_past_due": "Update your payment method to avoid losing Pro.",
+ "account.subscription_detail_grace": "Cloud data will be deleted at the end of the grace window; resubscribe to keep it.",
+ "account.subscription_detail_free": "Upgrade to Pro for cloud sync and voice input.",
+ "account.subscription_detail_coming_soon": "We're opening the billing channel — stay tuned.",
+ "account.subscription_action_subscribe": "Subscribe",
+ "account.subscription_action_manage": "Manage subscription",
+ "account.subscription_action_resume": "Resume subscription",
+ "account.subscription_action_update_card": "Update payment method",
+ "account.subscription_action_resubscribe": "Resubscribe",
+ "account.subscription_action_coming_soon": "Coming soon",
+ "account.subscription_warning_past_due": "Payment failed. Update your card on the management page.",
+ "account.subscription_warning_grace": "Cloud data will be deleted on {date}. Resubscribe to keep it.",
+ "account.subscription_open_failed": "Couldn't open the management page; check your network and retry.",
+ "account.pro_required_title": "Pro feature",
+ "account.pro_required_voice": "Voice input is a Pro feature. Subscribe to dictate directly into the composer with auto-transcription.",
+ "account.pro_required_sync": "Cloud sync is a Pro feature. Subscribe to keep conversations, agents, skills and knowledge in sync across devices.",
+ "account.pro_required_generic": "This is a Pro feature. Subscribe to unlock cloud sync and voice input.",
+ "account.pro_required_action": "Subscribe now",
+ "account.pro_required_cancel": "Later",
"common.ok": "OK",
"common.confirm": "Confirm",
"common.cancel": "Cancel",
@@ -33,6 +78,7 @@
"connectors.group.available": "Available",
"connectors.empty": "No connectors available.",
"connectors.action.connect": "Connect",
+ "connectors.action.connecting": "Connecting…",
"connectors.action.disconnect": "Disconnect",
"connectors.action.unavailable": "Coming soon",
"connectors.confirm_disconnect_title": "Disconnect \"{name}\"",
@@ -41,6 +87,7 @@
"connectors.errors.connect_failed": "Authorization failed",
"connectors.errors.remove_failed": "Uninstall failed",
"common.save": "Save",
+ "common.more": "More",
"common.loading": "Loading…",
"agents.label_connectors": "Allowed connectors",
"agents.connectors_empty": "No connectors installed. Add one in the Connectors tab.",
@@ -479,6 +526,9 @@
"settings.section.cloud": "Cloud",
"settings.section.local": "Local",
"settings.sync.title": "Cloud sync",
+ "settings.sync.pro_badge": "Pro",
+ "settings.sync.pro_required": "Cloud sync is a Pro feature. Subscribe to keep conversations, agents, skills and knowledge in sync across devices.",
+ "settings.sync.grace_warning": "Cloud sync paused. Cloud data will be deleted on {date}. Resubscribe to keep it.",
"settings.sync.storage_title": "Storage",
"settings.sync.conflicts_title": "Conflict log",
"settings.sync.conflicts_sub": "When two devices edit the same file at once, the overwritten version is kept here.",
@@ -505,6 +555,8 @@
"settings.sync.state_paused_login_required": "Sign in to enable",
"settings.sync.state_paused_quota_full": "Quota full",
"settings.sync.state_paused_offline": "Offline",
+ "settings.sync.state_paused_version_outdated": "App update required",
+ "settings.sync.version_outdated_hint": "Update this app to the latest version to resume sync.",
"settings.sync.last_sync": "Last synced: ",
"settings.sync.just_now": "just now",
"settings.sync.uploading": "up",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 92322e70..7c7b3746 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -1,4 +1,49 @@
{
+ "account.gate_title": "登录到 Orkas",
+ "account.gate_signin": "登录",
+ "account.gate_signin_pending": "正在打开授权页…",
+ "account.gate_signin_again": "重新打开授权页",
+ "account.gate_signing_in": "正在登录…",
+ "account.gate_browser_hint": "已在浏览器中打开授权页,授权后自动返回。",
+ "account.gate_sub": "登录账号后继续使用",
+ "account.gate_hint": "在打开的浏览器中完成授权,会自动返回应用",
+ "account.provider_google": "使用 Google 登录",
+ "account.provider_apple": "使用 Apple 登录",
+ "account.provider_generic": "使用 {provider} 登录",
+ "account.error_start": "无法开始登录,请稍后重试",
+ "account.error_cancelled": "授权已取消",
+ "account.error_generic": "登录失败",
+ "account.settings_title": "账号",
+ "account.settings_logout": "退出登录",
+ "account.settings_signed_in": "已登录",
+ "account.subscription_title": "会员",
+ "account.subscription_status_active": "续订时间",
+ "account.subscription_status_will_cancel": "到期时间",
+ "account.subscription_status_past_due": "扣款失败",
+ "account.subscription_status_expired": "会员已结束",
+ "account.subscription_status_free": "免费用户",
+ "account.subscription_status_coming_soon": "Pro 即将上线",
+ "account.subscription_detail_active": "云端同步与语音输入已解锁。",
+ "account.subscription_detail_will_cancel": "本期内仍可使用全部 Pro 功能;到期后切回免费。",
+ "account.subscription_detail_past_due": "请尽快更新支付方式以避免会员中断。",
+ "account.subscription_detail_grace": "云端数据将在保留期满后清理。续订即可恢复。",
+ "account.subscription_detail_free": "升级到 Pro 即可使用云端同步与语音输入。",
+ "account.subscription_detail_coming_soon": "我们正在开放支付通道,敬请期待。",
+ "account.subscription_action_subscribe": "开通会员",
+ "account.subscription_action_manage": "管理订阅",
+ "account.subscription_action_resume": "恢复订阅",
+ "account.subscription_action_update_card": "更新支付方式",
+ "account.subscription_action_resubscribe": "续订会员",
+ "account.subscription_action_coming_soon": "敬请期待",
+ "account.subscription_warning_past_due": "扣款失败,请到管理页更新支付方式。",
+ "account.subscription_warning_grace": "云端数据将于 {date} 清理,续订即可保留。",
+ "account.subscription_open_failed": "无法打开管理页,请检查网络后重试。",
+ "account.pro_required_title": "Pro 会员功能",
+ "account.pro_required_voice": "语音输入是 Pro 会员功能。开通后即可在对话框直接说话,自动转写为文字。",
+ "account.pro_required_sync": "云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。",
+ "account.pro_required_generic": "该功能是 Pro 会员专属。开通后即可使用云端同步与语音输入。",
+ "account.pro_required_action": "立即开通",
+ "account.pro_required_cancel": "稍后再说",
"common.ok": "确定",
"common.confirm": "确认",
"common.cancel": "取消",
@@ -12,14 +57,14 @@
"common.remove": "移除",
"common.dev_suffix": "(开发)",
"component.enabled": "已启用",
- "component.disabled": "已禁用",
+ "component.disabled": "已停用",
"component.enable": "启用",
- "component.disable": "禁用",
- "component.toggle_disable_hint": "点击禁用",
+ "component.disable": "停用",
+ "component.toggle_disable_hint": "点击停用",
"component.toggle_enable_hint": "点击启用",
"component.toggle_failed": "切换失败",
- "component.send_blocked_disabled": "该智能体已被禁用,请重新启用或换一个对话",
- "component.conv_agent_disabled_banner": "本对话绑定的智能体已被禁用,发送已锁定。在「智能体」页重新启用即可继续。",
+ "component.send_blocked_disabled": "该智能体已被停用,请重新启用或换一个对话",
+ "component.conv_agent_disabled_banner": "本对话绑定的智能体已被停用,发送已锁定。在「智能体」页重新启用即可继续。",
"sidebar.search": "搜索",
"sidebar.search_title": "全局搜索 (⌘K)",
"sidebar.new_chat": "指挥官",
@@ -33,6 +78,7 @@
"connectors.group.available": "可用",
"connectors.empty": "暂无可用连接器。",
"connectors.action.connect": "连接",
+ "connectors.action.connecting": "连接中…",
"connectors.action.disconnect": "断开",
"connectors.action.unavailable": "敬请期待",
"connectors.confirm_disconnect_title": "断开「{name}」",
@@ -41,6 +87,7 @@
"connectors.errors.connect_failed": "授权失败",
"connectors.errors.remove_failed": "卸载失败",
"common.save": "保存",
+ "common.more": "更多",
"common.loading": "加载中…",
"agents.label_connectors": "可用连接器",
"agents.connectors_empty": "尚未安装任何连接器。请在「连接器」tab 添加。",
@@ -479,6 +526,9 @@
"settings.section.cloud": "云端",
"settings.section.local": "本地",
"settings.sync.title": "云端同步",
+ "settings.sync.pro_badge": "Pro",
+ "settings.sync.pro_required": "云端同步是 Pro 会员功能。开通后多台设备的对话、智能体、技能、知识库自动保持一致。",
+ "settings.sync.grace_warning": "云端同步已暂停。云端数据将于 {date} 清理,续订即可保留。",
"settings.sync.storage_title": "存储空间",
"settings.sync.conflicts_title": "冲突记录",
"settings.sync.conflicts_sub": "多设备并发修改同一文件时,被覆盖的版本会保留在此。",
@@ -505,6 +555,8 @@
"settings.sync.state_paused_login_required": "需登录",
"settings.sync.state_paused_quota_full": "配额已满",
"settings.sync.state_paused_offline": "离线",
+ "settings.sync.state_paused_version_outdated": "应用版本过旧",
+ "settings.sync.version_outdated_hint": "请将本应用更新到最新版本后才能继续同步。",
"settings.sync.last_sync": "上次同步:",
"settings.sync.just_now": "刚刚",
"settings.sync.uploading": "上传",
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index 9e2093ba..505f26b7 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -88,6 +88,12 @@ function _saveLastView(view, cid) {
}
function _restoreLastView() {
+ // Restart policy: only `conversation` view is remembered across launches.
+ // Every other tab (agents / skills / contexts / connectors / apps / settings
+ // / project detail / marketplace / devtools) intentionally falls back to
+ // the commander (new-chat) — the user always lands on a known starting
+ // point and doesn't accidentally resume a settings / inventory tab they
+ // wandered into before quitting.
let saved = null;
try {
const raw = localStorage.getItem(_LAST_VIEW_KEY);
@@ -101,20 +107,6 @@ function _restoreLastView() {
setView('conversation', cid);
return;
}
- // Project detail page: cid slot carries the pid (see boot.js setView).
- // Verify the project still exists (might have been deleted on another
- // device since last save) before restoring; fall through to new-chat
- // otherwise.
- if (view === 'project' && cid
- && Array.isArray(_projectsCache)
- && _projectsCache.some((p) => p && p.project_id === cid)) {
- setView('project', cid);
- return;
- }
- if (view === 'agents' || view === 'skills' || view === 'contexts' || view === 'new-chat') {
- setView(view);
- return;
- }
setView('new-chat');
}
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index 747d4584..ed1bb818 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -22,6 +22,12 @@ let _connectorsState = {
catalog: [],
instances: [],
loading: false,
+ /** Per-card connecting flag. Set when `_runConnect` is in flight (browser-open → deep-link
+ * return → /oauth/exchange → MCP connect → list_tools). Visible only post-return when the
+ * user comes back to PC and the IPC is still running through exchange + MCP setup — without
+ * this they'd see a static "连接" button with no indication anything is happening. Button
+ * stays clickable; re-click supersedes the prior flow (see comment in `_runConnect`). */
+ connecting: new Set(),
};
async function loadConnectors() {
@@ -46,6 +52,32 @@ function _instanceById(id) {
return _connectorsState.instances.find((i) => i.id === id) || null;
}
+// Build a synthetic ConnectorInstance for a bundle entry. Bundle entries have no real instance
+// (manager.connectViaOAuth provisions the N members instead) — but the renderer treats the
+// bundle as a single card, so we derive an instance-shaped object: status=connected iff all
+// members connected; account_label / enabled taken from the first member that has them.
+function _deriveBundleInstance(entry) {
+ const members = (entry.bundle_member_ids || []).map((id) => _instanceById(id)).filter(Boolean);
+ if (!members.length) return null; // no member installed yet → bundle shows as "available"
+ const allConnected = members.length === entry.bundle_member_ids.length
+ && members.every((m) => m.status && m.status.kind === 'connected');
+ const anyErrored = members.find((m) => m.status && m.status.kind === 'error');
+ const accountLabel = members.map((m) => m.oauth_grant && m.oauth_grant.account_label).find(Boolean) || '';
+ // For enabled: bundle is "enabled" iff every member is enabled (any disabled → show "停用-able").
+ const allEnabled = members.every((m) => m.enabled !== false);
+ return {
+ id: entry.id,
+ display_name: entry.display_name,
+ status: allConnected
+ ? { kind: 'connected', since: 0 }
+ : (anyErrored ? { kind: 'error', message: anyErrored.status.message, at: 0 } : { kind: 'connecting' }),
+ oauth_grant: accountLabel ? { account_label: accountLabel } : undefined,
+ enabled: allEnabled,
+ // Bundle marker so the click handlers fan out to all members.
+ _bundle_member_ids: entry.bundle_member_ids,
+ };
+}
+
function _renderConnectorsGrid() {
const gridView = document.getElementById('connectors-grid-view');
if (!gridView) return;
@@ -57,11 +89,27 @@ function _renderConnectorsGrid() {
const gridAvail = document.getElementById('connectors-grid-available');
const empty = document.getElementById('connectors-empty');
+ // Bundle handling — entries with `bundle_member_ids` are UI groupings. Members are hidden
+ // (they don't show as separate cards) so the user sees one card per logical product.
+ const bundleMemberIds = new Set();
+ for (const entry of _connectorsState.catalog) {
+ if (Array.isArray(entry.bundle_member_ids)) {
+ for (const m of entry.bundle_member_ids) bundleMemberIds.add(m);
+ }
+ }
+
// Partition catalog rows by whether there's a corresponding connected instance.
const connectedItems = [];
const availableItems = [];
for (const entry of _connectorsState.catalog) {
- const inst = _instanceById(entry.id);
+ if (bundleMemberIds.has(entry.id)) continue; // hide bundle members
+ let inst = _instanceById(entry.id);
+ // For bundle entries: derive a synthetic "connected" instance when ALL members are
+ // connected. The synthetic instance shape mirrors a real one so `_renderCatalogCard`
+ // doesn't care it's a bundle.
+ if (Array.isArray(entry.bundle_member_ids)) {
+ inst = _deriveBundleInstance(entry);
+ }
if (inst && inst.status && inst.status.kind === 'connected') {
connectedItems.push({ entry, instance: inst });
} else {
@@ -98,39 +146,54 @@ function _renderCatalogCard(entry, instance) {
const isOAuthPending = !!(e && e.unavailable_reason === 'oauth_pending');
const connected = !!(instance && instance.status && instance.status.kind === 'connected');
const errored = !!(instance && instance.status && instance.status.kind === 'error');
+ // `enabled` is per-user soft state attached by `connectors.list` IPC. Only meaningful for
+ // connected cards (un-connected ones have nothing to disable). Default true when missing.
+ const enabledFlag = instance && Object.prototype.hasOwnProperty.call(instance, 'enabled')
+ ? !!instance.enabled
+ : true;
const card = document.createElement('div');
- card.className = 'connector-card';
+ card.className = `connector-card${connected && !enabledFlag ? ' is-disabled' : ''}`;
card.dataset.id = e.id;
- // Brand SVG when available (white card, logo in native colors). The orphan-instance fallback
- // path (catalog entry got removed but instance config still exists locally) renders the first
- // two chars of the display_name on a neutral gray square.
const iconHtml = e.icon_svg
? `<div class="connector-card-icon is-svg">${e.icon_svg}</div>`
: `<div class="connector-card-icon is-fallback">${escapeHtml((e.display_name || '?').slice(0, 2).toUpperCase())}</div>`;
const desc = (getLang && getLang() === 'zh' ? e.description_zh : e.description_en) || e.description_en || e.description_zh || '';
- // Account label (e.g. "[email protected]") shows under the connector name when the OAuth grant
- // includes one — replaces the now-gone detail page as the only "which account is connected"
- // surface. Errored instances show the error msg in the same slot.
const accountLabel = (instance && instance.oauth_grant && instance.oauth_grant.account_label) || '';
const errorMsg = errored && instance && instance.status && instance.status.message;
- // No status badge next to the name — the foot button label + the error
- // secondary line already convey state; the badge was visual duplication.
+ // ⋯ menu lives on connected cards only — it hosts the destructive "断开" action so it stays
+ // one click away from accidental triggers. Un-connected / errored cards still surface the
+ // disconnect action as a bottom-row button (they need it visible to recover; the "停用" toggle
+ // doesn't apply when there's nothing to disable).
+ const menuHtml = connected
+ ? `<button class="connector-card-menu-btn" data-act="menu" aria-label="${escapeHtml(t('common.more') || '⋯')}">⋯</button>`
+ : '';
+
+ // Bottom-row action:
+ // - connected: 启用 / 停用 toggle (per-user soft switch — hides instance from LLM)
+ // - errored: 断开 (recover from a stuck error state)
+ // - oauth_pending: disabled "敬请期待"
+ // - default (uninstalled): 连接 (start OAuth)
let action = '';
if (isOAuthPending) {
action = `<button class="btn btn-sm" disabled>${escapeHtml(t('connectors.action.unavailable'))}</button>`;
} else if (connected) {
- action = `<button class="btn btn-sm btn-danger" data-act="disconnect">${escapeHtml(t('connectors.action.disconnect'))}</button>`;
+ const label = enabledFlag ? t('component.disable') : t('component.enable');
+ const cls = enabledFlag ? 'btn btn-sm' : 'btn btn-sm btn-primary';
+ action = `<button class="${cls}" data-act="toggle-enabled">${escapeHtml(label)}</button>`;
} else if (errored) {
action = `<button class="btn btn-sm btn-danger" data-act="disconnect">${escapeHtml(t('connectors.action.disconnect'))}</button>`;
} else {
- action = `<button class="btn btn-sm btn-primary" data-act="connect">${escapeHtml(t('connectors.action.connect'))}</button>`;
+ // Spinner while `_runConnect` is in flight. Button stays clickable (re-click supersedes).
+ const isConnecting = _connectorsState.connecting && _connectorsState.connecting.has(e.id);
+ const label = isConnecting ? t('connectors.action.connecting') : t('connectors.action.connect');
+ const spinner = isConnecting ? '<span class="btn-spinner"></span>' : '';
+ action = `<button class="btn btn-sm btn-primary${isConnecting ? ' is-loading' : ''}" data-act="connect">${spinner}${escapeHtml(label)}</button>`;
}
- // Secondary line: account label when connected, error msg when errored, none otherwise.
let secondaryHtml = '';
if (errorMsg) {
secondaryHtml = '<div class="connector-card-error"></div>';
@@ -145,6 +208,7 @@ function _renderCatalogCard(entry, instance) {
<div class="connector-card-name"></div>
${secondaryHtml}
</div>
+ ${menuHtml}
</div>
<div class="connector-card-desc muted"></div>
<div class="connector-card-foot">${action}</div>
@@ -163,11 +227,64 @@ function _renderCatalogCard(entry, instance) {
const act = btn.dataset.act;
if (act === 'connect') _runConnect(e);
else if (act === 'disconnect') _quickDisconnect(e, instance);
+ else if (act === 'menu') _openCardMenu(btn, e, instance);
+ else if (act === 'toggle-enabled') _toggleConnectorEnabled(e, instance, !enabledFlag);
});
});
return card;
}
+// Tiny absolute-positioned popover anchored under the ⋯ button — one item for now ("断开").
+// Closes on outside click / Esc / window scroll. Keeping it inline so we don't pull in a generic
+// menu primitive for one use site; if a second connector-card menu item ever lands, refactor.
+function _openCardMenu(anchorBtn, entry, instance) {
+ const existing = document.querySelector('.connector-card-menu-popover');
+ if (existing) { existing.remove(); return; }
+ const rect = anchorBtn.getBoundingClientRect();
+ const pop = document.createElement('div');
+ pop.className = 'connector-card-menu-popover';
+ pop.style.top = `${Math.round(rect.bottom + 4)}px`;
+ pop.style.left = `${Math.round(rect.right - 120)}px`;
+ pop.innerHTML = `<div class="connector-card-menu-item is-danger" data-act="disconnect">${escapeHtml(t('connectors.action.disconnect'))}</div>`;
+ document.body.appendChild(pop);
+
+ const close = () => {
+ pop.remove();
+ document.removeEventListener('mousedown', onOutside, true);
+ document.removeEventListener('keydown', onKey, true);
+ window.removeEventListener('scroll', close, true);
+ };
+ const onOutside = (ev) => { if (!pop.contains(ev.target) && ev.target !== anchorBtn) close(); };
+ const onKey = (ev) => { if (ev.key === 'Escape') close(); };
+ document.addEventListener('mousedown', onOutside, true);
+ document.addEventListener('keydown', onKey, true);
+ window.addEventListener('scroll', close, true);
+
+ pop.querySelector('[data-act="disconnect"]').addEventListener('click', () => {
+ close();
+ _quickDisconnect(entry, instance);
+ });
+}
+
+async function _toggleConnectorEnabled(entry, instance, nextEnabled) {
+ // Bundle entry: fan out the toggle to every member id; bundle itself isn't an instance.
+ const ids = Array.isArray(entry.bundle_member_ids) && entry.bundle_member_ids.length
+ ? entry.bundle_member_ids.slice()
+ : [(instance && instance.id) || entry.id];
+ try {
+ for (const id of ids) {
+ const res = await window.orkas.invoke('connectors.set_enabled', { id, enabled: nextEnabled });
+ if (!res || !res.ok) {
+ uiAlert((res && res.error) || t('component.toggle_failed'));
+ return;
+ }
+ }
+ await loadConnectors();
+ } catch (err) {
+ uiAlert((err && err.message) || t('component.toggle_failed'));
+ }
+}
+
function _entryFromInstance(instance) {
return {
id: instance.id,
@@ -178,19 +295,25 @@ function _entryFromInstance(instance) {
}
async function _quickDisconnect(entry, instance) {
- const id = (instance && instance.id) || entry.id;
- const name = (instance && instance.display_name) || entry.display_name || id;
+ const name = (instance && instance.display_name) || entry.display_name || entry.id;
const ok = await uiConfirmDanger({
title: t('connectors.confirm_disconnect_title', { name }),
message: t('connectors.confirm_disconnect_msg'),
dangerLabel: t('connectors.action.disconnect'),
});
if (!ok) return;
+ // Bundle entry: disconnect every member instance. Members not yet installed are skipped (the
+ // IPC just returns ok:false / removed:false which we treat as no-op).
+ const ids = Array.isArray(entry.bundle_member_ids) && entry.bundle_member_ids.length
+ ? entry.bundle_member_ids.slice()
+ : [(instance && instance.id) || entry.id];
try {
- const res = await window.orkas.invoke('connectors.remove', { id });
- if (!res || !res.ok) {
- uiAlert((res && res.error) || t('connectors.errors.remove_failed'));
- return;
+ for (const id of ids) {
+ const res = await window.orkas.invoke('connectors.remove', { id });
+ if (!res || (!res.ok && !/not found/i.test(res.error || ''))) {
+ uiAlert((res && res.error) || t('connectors.errors.remove_failed'));
+ return;
+ }
}
await loadConnectors();
} catch (err) {
@@ -199,10 +322,15 @@ async function _quickDisconnect(entry, instance) {
}
async function _runConnect(entry) {
- // No UI state mutation here — the card stays as-is. Re-clicks supersede the prior pending
- // flow on the main side (oauth.ts::startOAuth calls _cancelPending before installing a new
- // listener), and the prior _runConnect's await rejects with "superseded ..." which we
- // silently drop.
+ // Mark "connecting" so the card's foot button shows a spinner. The button stays clickable —
+ // re-clicks supersede the prior pending flow on the main side (oauth.ts::startOAuth calls
+ // _cancelPending before installing a new listener), and the prior _runConnect's await
+ // rejects with "superseded ..." which we silently drop. The spinner is mainly for the
+ // post-deep-link-return phase (exchange / MCP connect / list_tools — multiple network
+ // roundtrips that look frozen if we render nothing). During the browser-open phase the user
+ // isn't looking at the PC anyway.
+ _connectorsState.connecting.add(entry.id);
+ _renderConnectorsGrid();
try {
const res = await window.orkas.invoke('connectors.start_oauth', { catalog_id: entry.id });
if (res && res.ok && res.instance) {
@@ -221,6 +349,12 @@ async function _runConnect(entry) {
uiAlert((err && err.message) || t('connectors.errors.connect_failed'));
}
await loadConnectors();
+ } finally {
+ _connectorsState.connecting.delete(entry.id);
+ // `loadConnectors` already re-renders, but it's inside the try/catch and may have skipped
+ // (e.g. on `superseded` we don't always reload). Belt-and-suspenders: ensure the spinner
+ // clears even when the connect flow exits without a reload.
+ _renderConnectorsGrid();
}
}
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index d393f6e5..e20c3887 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -46,6 +46,16 @@ async function loadSettings() {
_settingsRenderCommanderAvatar();
_settingsRenderMetacognition();
_settingsRenderDataRoot();
+ // Account card + subscription card (views/login/account_settings.js — absent in
+ // OrkasOpen, so these are no-ops there). renderSubscriptionSettings rebinds the
+ // action button's click handler with the current subscription state on every
+ // render — opening the panel is the canonical "guarantee fresh button binding"
+ // moment, so call it explicitly here (not just from the account.onChange listener
+ // which only fires on state changes — for a Free user with no transitions the
+ // listener never fires after boot, leaving the button bound to whatever its
+ // first render captured).
+ if (typeof renderAccountSettings === 'function') renderAccountSettings();
+ if (typeof renderSubscriptionSettings === 'function') renderSubscriptionSettings();
}
// ── Commander avatar ──
diff --git a/src/renderer/style.css b/src/renderer/style.css
index b91cd624..4c9ff591 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -17,6 +17,40 @@
* { box-sizing: border-box; margin: 0; padding: 0; }
+/* ─── Global scrollbar — thin, subtle. Without this rule, any scrollable
+ container that doesn't have its own ::-webkit-scrollbar override (e.g.
+ settings panels, sync usage breakdown, generic modal bodies) falls
+ back to the OS default — on macOS that's a chunky ~15px bar that
+ looks out of place against the app's compact, soft-shadowed UI.
+ Per-element overrides further down the file (.projects-list,
+ .conversation-list, .skills-grid-scroll, etc.) keep their tighter
+ 4–6px widths via CSS specificity; this rule only catches the
+ "no override declared" case. ─── */
+::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+::-webkit-scrollbar-track {
+ background: transparent;
+}
+::-webkit-scrollbar-thumb {
+ background: rgba(15, 23, 42, 0.16);
+ border-radius: 8px;
+ border: 2px solid transparent;
+ background-clip: padding-box;
+}
+::-webkit-scrollbar-thumb:hover {
+ background: rgba(15, 23, 42, 0.32);
+ background-clip: padding-box;
+}
+::-webkit-scrollbar-corner {
+ background: transparent;
+}
+* {
+ scrollbar-width: thin;
+ scrollbar-color: rgba(15, 23, 42, 0.16) transparent;
+}
+
body {
height: 100vh;
font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
@@ -5559,6 +5593,49 @@ body.model-not-configured .main-content { flex-direction: column; }
.settings-tab.has-dot.is-orange::after { background: #f59e0b; }
.settings-tab-pane[hidden] { display: none; }
+/* Subscription card (account tab). Layout: chip badge + status text on one
+ line, detail line beneath, action button on the right. Avatar slot omitted —
+ that slot is reserved for user identity in the Account card; using it for a
+ tier marker confused the visual hierarchy (FREE in a circle reads as a user
+ avatar). */
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 2px;
+}
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ padding: 2px 8px;
+ border-radius: 10px;
+ background: rgba(107, 114, 128, 0.12);
+ color: #4b5563;
+ text-transform: uppercase;
+}
+ background: #0a0a0a;
+ color: #fff;
+}
+ font-size: 14px;
+ color: var(--ink, #0a0a0a);
+}
+
+/* Pro feature badge — inline in a card title to mark "this is Pro-gated"
+ when the current user isn't a Pro subscriber. Same chip shape as the
+ subscription card's badge so the visual language stays consistent. */
+.settings-pro-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 1px 7px;
+ border-radius: 8px;
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ background: #0a0a0a;
+ color: #fff;
+ text-transform: uppercase;
+ vertical-align: 2px;
+}
+
/* Sync card (data tab). */
font-size: 12px;
padding: 2px 8px;
@@ -7163,6 +7240,64 @@ body.model-not-configured .main-content { flex-direction: column; }
-webkit-box-orient: vertical;
overflow: hidden;
}
+/* Connected card's ⋯ menu lives at the top-right of `.connector-card-top`. Hosts the destructive
+ "disconnect" action; kept off the visible foot row so it's one extra click away from the
+ common "enable / disable" toggle. */
+.connector-card-menu-btn {
+ margin-left: auto;
+ width: 28px;
+ height: 28px;
+ border: 0;
+ background: transparent;
+ border-radius: 6px;
+ font-size: 18px;
+ line-height: 1;
+ color: #6b7280;
+ cursor: pointer;
+ flex-shrink: 0;
+}
+.connector-card-menu-btn:hover { background: rgba(15, 23, 42, 0.06); color: #111827; }
+.connector-card-menu-popover {
+ position: fixed;
+ z-index: 1000;
+ background: #fff;
+ border: 1px solid rgba(15, 23, 42, 0.12);
+ border-radius: 8px;
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12);
+ min-width: 120px;
+ padding: 4px;
+}
+.connector-card-menu-item {
+ padding: 7px 10px;
+ border-radius: 6px;
+ font-size: 13px;
+ cursor: pointer;
+ user-select: none;
+}
+.connector-card-menu-item:hover { background: rgba(15, 23, 42, 0.05); }
+.connector-card-menu-item.is-danger { color: #dc2626; }
+.connector-card-menu-item.is-danger:hover { background: rgba(220, 38, 38, 0.08); }
+
+/* Disabled-but-connected card: muted look so the user can tell at a glance which connector
+ they've turned off, without removing it from the "Connected" group. */
+.connector-card.is-disabled { opacity: 0.55; }
+.connector-card.is-disabled .connector-card-icon { filter: saturate(0.4); }
+
+/* Inline spinner inside the "连接" button — shown post-deep-link return while the IPC is
+ running through `/oauth/exchange` + MCP `initialize` + `list_tools` (3 network roundtrips,
+ ~hundreds of ms to a few seconds). Button stays clickable; spinner just signals progress. */
+.btn-spinner {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ margin-right: 6px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.5);
+ border-top-color: rgba(255, 255, 255, 0.95);
+ vertical-align: -1px;
+ animation: marketplace-upload-spin 0.8s linear infinite;
+}
+
.connector-card-foot { margin-top: auto; display: flex; justify-content: flex-end; gap: 6px; align-items: center; }
.connector-card-foot .btn-link {
background: transparent;
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index 80ac784c..7462d9e8 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -109,6 +109,7 @@ describe('agents › normalizeAgent', () => {
description_zh: '', description_en: 'D',
workflow: 'W',
source: 'builtin', created_at: 't1', updated_at: 't2',
+ category: '',
// computed-at-load default; overridden by listAgents/getAgent at the boundary
enabled: true,
});
@@ -971,7 +972,7 @@ describe('agents › deleteCustomAgent', () => {
writeCustomAgent('victim');
const sessionDir = path.join(tmpDir, TEST_UID, 'cloud', 'sessions');
fs.mkdirSync(sessionDir, { recursive: true });
- const sessionFile = path.join(sessionDir, `${TEST_UID}-agent-victim.jsonl`);
+ const sessionFile = path.join(sessionDir, 'agent-victim.jsonl');
fs.writeFileSync(sessionFile, '{"role":"user","content":"old"}\n');
const a = await loadAgents();
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index 8c21b832..e4bc3f37 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -47,7 +47,7 @@ describe('chats › createConversation', () => {
const chats = await loadChats();
const conv = await chats.createConversation(TEST_UID, { title: 't1' });
expect(conv.conversation_id).toMatch(/^[0-9a-f]{12}$/);
- expect(conv.session_id).toBe(`${TEST_UID}-gconv-${conv.conversation_id}`);
+ expect(conv.session_id).toBe(`gconv-${conv.conversation_id}`);
const idx = JSON.parse(fs.readFileSync(
path.join(tmpDir, TEST_UID, 'cloud', 'chats', '_index.json'), 'utf-8'));
expect(idx[0].conversation_id).toBe(conv.conversation_id);
@@ -70,7 +70,7 @@ describe('chats › createConversation', () => {
const c1 = await chats.createConversation(TEST_UID, { projectId: 'p_aabbccdd' });
expect(c1.project_id).toBe('p_aabbccdd');
// session_id MUST stay independent of project_id.
- expect(c1.session_id).toBe(`${TEST_UID}-gconv-${c1.conversation_id}`);
+ expect(c1.session_id).toBe(`gconv-${c1.conversation_id}`);
const c2 = await chats.createConversation(TEST_UID);
expect(c2.project_id).toBeUndefined();
diff --git a/test/main/features/group_chat/plan_executor.test.ts b/test/main/features/group_chat/plan_executor.test.ts
index 44c44d49..b628be6c 100644
--- a/test/main/features/group_chat/plan_executor.test.ts
+++ b/test/main/features/group_chat/plan_executor.test.ts
@@ -139,13 +139,13 @@ describe('plan_executor › sequential pipeline + variable substitution', () =>
// Each agent yields a final text we'll later assert appears in downstream
// step input (verifies template substitution worked).
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'final', text: '需求摘要: 做一个 markdown 笔记软件' },
]);
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, B_ID), [
+ _setScript(state.buildGmemberSessionId(cid, B_ID), [
{ type: 'final', text: '设计要点: 使用 Electron + Markdown-it' },
]);
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, C_ID), [
+ _setScript(state.buildGmemberSessionId(cid, C_ID), [
{ type: 'final', text: '代码已落地: 主框架 + 编辑器组件' },
]);
@@ -201,17 +201,17 @@ describe('plan_executor › parallel fork + synthesis', () => {
const cid = newCid();
const state = await import('../../../../src/main/features/group_chat/state');
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'final', text: 'Alpha 视角: 看好' },
]);
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, B_ID), [
+ _setScript(state.buildGmemberSessionId(cid, B_ID), [
{ type: 'final', text: 'Beta 视角: 风险大' },
]);
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, C_ID), [
+ _setScript(state.buildGmemberSessionId(cid, C_ID), [
{ type: 'final', text: 'Gamma 视角: 折衷' },
]);
// Commander synthesis turn.
- _setScript(state.buildGconvSessionId(TEST_UID, cid), [
+ _setScript(state.buildGconvSessionId(cid), [
{ type: 'final', text: '综合三方观点:可行但需谨慎。' },
]);
@@ -272,10 +272,10 @@ describe('plan_executor › failure policies', () => {
const state = await import('../../../../src/main/features/group_chat/state');
// A returns an error (we route this through the bus's stream-error path).
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'error', text: 'A failed for testing', aborted: false },
]);
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, B_ID), [
+ _setScript(state.buildGmemberSessionId(cid, B_ID), [
{ type: 'final', text: 'B succeeded despite A failing' },
]);
@@ -299,11 +299,11 @@ describe('plan_executor › failure policies', () => {
const cid = newCid();
const state = await import('../../../../src/main/features/group_chat/state');
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'error', text: 'A failed', aborted: false },
]);
// B's script — should never get consumed since plan aborts.
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, B_ID), [
+ _setScript(state.buildGmemberSessionId(cid, B_ID), [
{ type: 'final', text: 'B should not run' },
]);
@@ -338,7 +338,7 @@ describe('plan_executor › user-assignee step', () => {
const state = await import('../../../../src/main/features/group_chat/state');
const bus = await import('../../../../src/main/features/group_chat/bus');
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'final', text: '收到 user 的补充:' },
]);
@@ -398,7 +398,7 @@ describe('plan_executor › agent form pauses the step (not "done")', () => {
const bus = await import('../../../../src/main/features/group_chat/bus');
// First A turn: emit a form (no real work yet).
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{
type: 'final',
text: '需要你确认几个字段:\n\n```agent-input-form\n{"fields":[{"id":"goal","label":"目标","type":"text"}]}\n```',
@@ -426,10 +426,10 @@ describe('plan_executor › agent form pauses the step (not "done")', () => {
expect(lines.find((l) => l.from === 'commander' && l.to.includes(B_ID))).toBeUndefined();
// Now A's NEXT turn (after user submits form): real work, no form.
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'final', text: '需求已整理:目标是 X' },
]);
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, B_ID), [
+ _setScript(state.buildGmemberSessionId(cid, B_ID), [
{ type: 'final', text: 'B 完成' },
]);
@@ -455,7 +455,7 @@ describe('plan_executor › auto plan_update', () => {
const cid = newCid();
const state = await import('../../../../src/main/features/group_chat/state');
- _setScript(state.buildGmemberSessionId(TEST_UID, cid, A_ID), [
+ _setScript(state.buildGmemberSessionId(cid, A_ID), [
{ type: 'final', text: 'A done' },
]);
diff --git a/test/main/features/group_chat/state.test.ts b/test/main/features/group_chat/state.test.ts
index 8fc9b4b6..a824bd7a 100644
--- a/test/main/features/group_chat/state.test.ts
+++ b/test/main/features/group_chat/state.test.ts
@@ -23,19 +23,21 @@ afterEach(() => {
});
describe('group_chat state › sessionId builders', () => {
+ // session_id format is `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id; user
+ // scoping comes from the path root `<activeUid>/cloud/sessions/<sid>.jsonl`).
it('build commander / member session ids with the right kind segment', async () => {
const s = await import('../../../../src/main/features/group_chat/state');
- expect(s.buildGconvSessionId('u1', 'cidA')).toBe('u1-gconv-cidA');
- expect(s.buildGmemberSessionId('u1', 'cidA', 'agentX')).toBe('u1-gmember-cidA-agentX');
+ expect(s.buildGconvSessionId('cidA')).toBe('gconv-cidA');
+ expect(s.buildGmemberSessionId('cidA', 'agentX')).toBe('gmember-cidA-agentX');
});
it('actorSessionId routes commander → gconv, agent → gmember, user → throw', async () => {
const s = await import('../../../../src/main/features/group_chat/state');
- expect(s.actorSessionId('u1', 'cidA', { kind: 'commander', id: 'commander', joined_at: 't' }))
- .toBe('u1-gconv-cidA');
- expect(s.actorSessionId('u1', 'cidA', { kind: 'agent', id: 'agentX', joined_at: 't' }))
- .toBe('u1-gmember-cidA-agentX');
- expect(() => s.actorSessionId('u1', 'cidA', { kind: 'user', id: 'user', joined_at: 't' })).toThrow();
+ expect(s.actorSessionId('cidA', { kind: 'commander', id: 'commander', joined_at: 't' }))
+ .toBe('gconv-cidA');
+ expect(s.actorSessionId('cidA', { kind: 'agent', id: 'agentX', joined_at: 't' }))
+ .toBe('gmember-cidA-agentX');
+ expect(() => s.actorSessionId('cidA', { kind: 'user', id: 'user', joined_at: 't' })).toThrow();
});
});
diff --git a/test/main/features/local_agents/runner.test.ts b/test/main/features/local_agents/runner.test.ts
index f7f550d9..8cd5ed65 100644
--- a/test/main/features/local_agents/runner.test.ts
+++ b/test/main/features/local_agents/runner.test.ts
@@ -272,8 +272,9 @@ describe('local_agents/runner', () => {
expect(fs.existsSync(toolEvent.outputPath)).toBe(true);
expect(fs.readFileSync(toolEvent.outputPath, 'utf8')).toBe(big);
// Spill landed under the expected per-session directory shape:
- // <uid>/local/tool-results/<uid>-cli-claude-<runId>/bash.<id>.txt
- expect(toolEvent.outputPath).toContain(`${TEST_UID}-cli-claude-${result.runId}`);
+ // <uid>/local/tool-results/cli-claude-<runId>/bash.<id>.txt (CLAUDE.md §5 — session_id
+ // dropped uid prefix; user scoping comes from path root, not the filename)
+ expect(toolEvent.outputPath).toContain(`cli-claude-${result.runId}`);
expect(toolEvent.outputPath).toMatch(/bash\.[0-9a-f]+\.txt$/);
});
diff --git a/test/main/features/projects.test.ts b/test/main/features/projects.test.ts
index 5840f8ee..9f45101c 100644
--- a/test/main/features/projects.test.ts
+++ b/test/main/features/projects.test.ts
@@ -45,7 +45,7 @@ describe('projects › createProject', () => {
const r = await projects.createProject(TEST_UID, ' My Project ');
expect(r.ok).toBe(true);
if (!r.ok) return;
- expect(r.project.project_id).toMatch(/^p_[0-9a-f]{8}$/);
+ expect(r.project.project_id).toMatch(/^p_[0-9a-f]{12}$/);
expect(r.project.name).toBe('My Project'); // trimmed
expect(r.project.owner_uid).toBe(TEST_UID);
expect(r.project.created_at).toBeTruthy();
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 2cff609b..410bafed 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -504,7 +504,7 @@ describe('skills › listSkills', () => {
const s = await loadSkills();
const list = await s.listSkills();
expect(list).toEqual([
- { id: 'alpha', name: 'Alpha', source: 'custom', description_zh: '', description_en: 'The first', enabled: true },
+ { id: 'alpha', name: 'Alpha', source: 'custom', description_zh: '', description_en: 'The first', category: '', create_uid: undefined, enabled: true },
]);
});
@@ -538,6 +538,7 @@ describe('skills › getCustomSkill', () => {
name: 'Alpha',
description_zh: '',
description_en: 'desc',
+ category: '',
source: 'custom',
dir: path.join(customSkillsDir(), 'alpha'),
});
@@ -622,7 +623,7 @@ describe('skills › deleteCustomSkill', () => {
writeCustomSkill('target');
const sessionDir = path.join(tmpDir, TEST_UID, 'cloud', 'sessions');
fs.mkdirSync(sessionDir, { recursive: true });
- const sessionFile = path.join(sessionDir, `${TEST_UID}-skill-target.jsonl`);
+ const sessionFile = path.join(sessionDir, 'skill-target.jsonl');
fs.writeFileSync(sessionFile, '{"role":"user","content":"old"}\n');
const s = await loadSkills();
diff --git a/test/main/features/users.test.ts b/test/main/features/users.test.ts
index 7363b398..b4fb68c9 100644
--- a/test/main/features/users.test.ts
+++ b/test/main/features/users.test.ts
@@ -123,3 +123,4 @@ describe('features/users › initActiveUser', () => {
expect(rec.created_at).toBe('2026-01-01T00:00:00');
});
});
+
diff --git a/test/main/model/core-agent/connector-meta-tools.test.ts b/test/main/model/core-agent/connector-meta-tools.test.ts
index d22c5fb2..73cd86d0 100644
--- a/test/main/model/core-agent/connector-meta-tools.test.ts
+++ b/test/main/model/core-agent/connector-meta-tools.test.ts
@@ -115,95 +115,75 @@ async function runTool(tool: { execute: (input: any, ctx: any) => Promise<any> }
}
// ── connectorExposureFromSessionId (the runner.ts session-kind gate) ────
+//
+// session_id is now `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id, since the
+// path root `<activeUid>/{cloud,local}/sessions/<sid>.jsonl` already scopes by user). The
+// gate just looks at the kind keyword anchored at the start.
describe('connectorExposureFromSessionId', () => {
- // Real-world archive sample that broke the prior anchored-regex implementation: uid is a
- // UUID with internal dashes. The buggy `^[^-]+-(gconv|gmember)-/` only captured the first
- // hex group (`D69594E0`) and rejected the rest, returning 'none' on every UUID-uid session.
- it('matches gconv with a UUID-shaped uid (regression: UUID-uid sessions used to be rejected)', async () => {
+ it('matches gconv (commander) → tools+block', async () => {
const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(connectorExposureFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-gconv-ac5559863d42')).toBe('tools+block');
+ expect(connectorExposureFromSessionId('gconv-ac5559863d42')).toBe('tools+block');
});
- it('matches gmember with a UUID-shaped uid + dashed cid + dashed aid', async () => {
+ it('matches gmember (agent worker) including dashed aid in the tail → tools+block', async () => {
const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(connectorExposureFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-gmember-cv-1-agt-42')).toBe('tools+block');
+ expect(connectorExposureFromSessionId('gmember-cv1-agt-42')).toBe('tools+block');
});
- it('matches agent-edit with a UUID-shaped uid', async () => {
+ it('matches agent-edit → discover+block (block + list_connector_tools, NO call_connector_tool)', async () => {
const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(connectorExposureFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-agent-agt-7')).toBe('block-only');
- });
-
- it('still matches the legacy 8-digit-numeric uid shape (CLAUDE.md §4)', async () => {
- const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(connectorExposureFromSessionId('99999999-gconv-cv1')).toBe('tools+block');
- expect(connectorExposureFromSessionId('99999999-gmember-cv1-agt-1')).toBe('tools+block');
- expect(connectorExposureFromSessionId('99999999-agent-agt-1')).toBe('block-only');
+ expect(connectorExposureFromSessionId('agent-agt-7')).toBe('discover+block');
});
it('returns none for non-task session kinds (skill / extract-img / cli / reflect / memory-extract / anon)', async () => {
const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(connectorExposureFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-skill-sk1')).toBe('none');
- expect(connectorExposureFromSessionId('99999999-skill-sk1')).toBe('none');
- expect(connectorExposureFromSessionId('99999999-extract-img-deadbeef')).toBe('none');
- expect(connectorExposureFromSessionId('99999999-cli-claude-run-1')).toBe('none');
- expect(connectorExposureFromSessionId('99999999-reflect-x')).toBe('none');
- expect(connectorExposureFromSessionId('99999999-memory-extract-x')).toBe('none');
- expect(connectorExposureFromSessionId('99999999-anon')).toBe('none');
- });
-});
-
-// ── extractUidFromSessionId (anchors on the kind keyword, not first `-`) ─
-
-describe('extractUidFromSessionId', () => {
- it('returns the full UUID-shaped uid (regression: prior `^([^-]+)-` regex truncated it to the first hex group)', async () => {
- const { extractUidFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(extractUidFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-gconv-ac5559863d42'))
- .toBe('D69594E0-CF31-424C-9318-30231197E3A9');
- });
-
- it('returns the 8-digit numeric uid (CLAUDE.md §4 legacy shape)', async () => {
- const { extractUidFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(extractUidFromSessionId('99999999-gconv-cv1')).toBe('99999999');
- expect(extractUidFromSessionId('99999999-gmember-cv1-agt-1')).toBe('99999999');
- expect(extractUidFromSessionId('99999999-skill-sk1')).toBe('99999999');
- expect(extractUidFromSessionId('99999999-agent-agt-1')).toBe('99999999');
- });
-
- it('handles dashed kind keywords (extract-img / memory-extract) without splitting them', async () => {
- const { extractUidFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(extractUidFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-extract-img-deadbeef'))
- .toBe('D69594E0-CF31-424C-9318-30231197E3A9');
- expect(extractUidFromSessionId('99999999-memory-extract-foo')).toBe('99999999');
- });
-
- it('handles kinds with no tail (-anon at end of string)', async () => {
- const { extractUidFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(extractUidFromSessionId('99999999-anon')).toBe('99999999');
- expect(extractUidFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-anon')).toBe('D69594E0-CF31-424C-9318-30231197E3A9');
- });
-
- it('returns null when no recognised kind keyword is present', async () => {
- const { extractUidFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
- expect(extractUidFromSessionId('justauidwithnokind')).toBeNull();
- expect(extractUidFromSessionId('')).toBeNull();
+ expect(connectorExposureFromSessionId('skill-sk1')).toBe('none');
+ expect(connectorExposureFromSessionId('extract-img-deadbeef')).toBe('none');
+ expect(connectorExposureFromSessionId('cli-claude-run-1')).toBe('none');
+ expect(connectorExposureFromSessionId('reflect-x')).toBe('none');
+ expect(connectorExposureFromSessionId('memory-extract-x')).toBe('none');
+ expect(connectorExposureFromSessionId('anon')).toBe('none');
+ expect(connectorExposureFromSessionId('anon-deadbeef')).toBe('none');
+ });
+
+ it('returns none when fed a legacy uid-prefixed session_id (regression: pre-migration leftovers must not silently match)', async () => {
+ // Legacy `<uid>-<kind>-<tail>` files should be renamed by `migrateLegacySessionIds` before
+ // the runner ever sees them. If one slips through, the gate returning 'none' is safer than
+ // a partial substring match that would expose the wrong tools.
+ const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');
+ expect(connectorExposureFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-gconv-cv1')).toBe('none');
+ expect(connectorExposureFromSessionId('99999999-agent-agt-1')).toBe('none');
});
});
-// ── createConnectorMetaTools shape (now async + conditional) ────────────
+// ── createConnectorMetaTools shape (mode-gated tri-state) ───────────────
describe('createConnectorMetaTools', () => {
- it('returns the two meta-tools when at least one connector is visible', async () => {
+ it('full mode: returns both meta-tools when at least one connector is visible', async () => {
fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];
const { createConnectorMetaTools } = await loadModule();
- const tools = await createConnectorMetaTools({ userId: UID });
+ const tools = await createConnectorMetaTools({ userId: UID }, 'full');
expect(tools.map((t) => t.name)).toEqual([
'list_connector_tools',
'call_connector_tool',
]);
});
+ it('discover mode: returns only list_connector_tools (no call) — agent-edit shape', async () => {
+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];
+ const { createConnectorMetaTools } = await loadModule();
+ const tools = await createConnectorMetaTools({ userId: UID }, 'discover');
+ expect(tools.map((t) => t.name)).toEqual(['list_connector_tools']);
+ });
+
+ it('full is the default when mode is omitted', async () => {
+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];
+ const { createConnectorMetaTools } = await loadModule();
+ const tools = await createConnectorMetaTools({ userId: UID });
+ expect(tools.length).toBe(2);
+ });
+
it('returns [] when no connector is visible (commander, no instances installed)', async () => {
fixtures.instances = [];
const { createConnectorMetaTools } = await loadModule();
@@ -278,23 +258,27 @@ describe('getConnectorPromptBlock', () => {
expect(githubLine).not.toContain('account:');
});
- it('omits status suffix on the healthy `connected` case (keeps lines short)', async () => {
+ it('never emits a status suffix — the block only contains connected instances by design', async () => {
fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];
const { getConnectorPromptBlock } = await loadModule();
const block = await getConnectorPromptBlock(UID, undefined);
- expect(block).not.toContain('connected');
- expect(block).not.toContain('disconnected');
+ expect(block).not.toMatch(/—\s*(connected|disconnected|connecting|error)/i);
+ expect(block).not.toMatch(/ask user to refresh/i);
});
- it('appends a status suffix only when not connected (lets the model surface the issue)', async () => {
+ it('non-connected instances are filtered out entirely (not just status-suffixed)', async () => {
fixtures.instances = [
- makeInstance({ id: 'notion', tools: NOTION_TOOLS, status: { kind: 'disconnected' } }),
+ makeInstance({ id: 'notion', tools: NOTION_TOOLS, status: { kind: 'disconnected' } }),
+ makeInstance({ id: 'github', tools: GITHUB_TOOLS, status: { kind: 'error', message: 'boom', at: 0 } }),
+ makeInstance({ id: 'gmail', tools: [], status: { kind: 'connecting' } }),
+ makeInstance({ id: 'slack', tools: [], status: { kind: 'connected', since: 0 } }),
];
const { getConnectorPromptBlock } = await loadModule();
const block = await getConnectorPromptBlock(UID, undefined);
- expect(block).toContain('**notion**');
- expect(block).toContain('disconnected');
- expect(block).toMatch(/ask user to refresh/i);
+ expect(block).toContain('**slack**');
+ expect(block).not.toContain('**notion**');
+ expect(block).not.toContain('**github**');
+ expect(block).not.toContain('**gmail**');
});
it('falls back to display_name only when the catalog has no description (defensive)', async () => {
@@ -372,9 +356,10 @@ describe('list_connector_tools', () => {
expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');
});
- it('disconnected connector → E_CONNECTOR_NOT_CONNECTED', async () => {
- // Need at least one connected instance so the meta-tools array isn't empty; then
- // also include a disconnected one to exercise the per-call branch.
+ it('disconnected connector → invisible at the meta-tool, surfaces as E_CONNECTOR_NOT_VISIBLE', async () => {
+ // Under the live-state filter (`resolveVisibleConnectors` keeps only connected instances),
+ // a disconnected instance never reaches the per-call branch — the model sees the same
+ // error code as for an unknown id, and `## Connectors` doesn't list it either.
fixtures.instances = [
makeInstance({ id: 'github', tools: GITHUB_TOOLS }),
makeInstance({ id: 'notion', tools: NOTION_TOOLS, status: { kind: 'disconnected' } }),
@@ -383,7 +368,7 @@ describe('list_connector_tools', () => {
const [listTools] = await createConnectorMetaTools({ userId: UID });
const r = await runTool(listTools, { connector_id: 'notion' });
expect(r.isError).toBe(true);
- expect(r.content).toContain('E_CONNECTOR_NOT_CONNECTED');
+ expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');
});
it('missing connector_id → E_BAD_INPUT', async () => {
diff --git a/test/main/model/session-store.test.ts b/test/main/model/session-store.test.ts
index eef0cbde..83efe563 100644
--- a/test/main/model/session-store.test.ts
+++ b/test/main/model/session-store.test.ts
@@ -3,16 +3,16 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-// Session-store path routing — no LLM calls here, just `sessionFileFor`
-// plumbing. The gate guards a real bug we fixed earlier: extract/organizer
-// session jsonls used to land in a shared top-level dir (feature name in
-// the first segment instead of the uid), which leaked across users.
+// Session-store path routing — no LLM calls here, just `sessionFileFor` plumbing. The format
+// is now `<kind>-<tail>` (CLAUDE.md §5 — uid no longer in session_id, since the path root
+// `<activeUid>/{cloud,local}/sessions/<sid>.jsonl` already scopes by user). The router picks
+// cloud vs local based on whether the kind is ephemeral (extract-img / reflect / memory-extract
+// / anon → local; gconv / gmember / skill / agent → cloud).
//
-// CRITICAL: this file previously called `activateUser(uid)` in `beforeAll`
-// WITHOUT setting ORKAS_WORKSPACE_ROOT first, so the real `PC/data/`
-// received a `data/<uid>/` skeleton + a rewritten `users.json` every time
-// the test suite ran. Reproduce the fix by keeping the workspace pinned to
-// a per-run tmp dir and resetting the module graph so `paths.ts` picks it
+// CRITICAL: this file previously called `activateUser(uid)` in `beforeAll` WITHOUT setting
+// ORKAS_WORKSPACE_ROOT first, so the real `PC/data/` received a `data/<uid>/` skeleton + a
+// rewritten `users.json` every time the test suite ran. Reproduce the fix by keeping the
+// workspace pinned to a per-run tmp dir and resetting the module graph so `paths.ts` picks it
// up before anything imports `users`.
let tmpDir: string;
@@ -33,106 +33,94 @@ afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
-// `sessionFileFor` and `WS_ROOT` must be dynamic-imported inside each test
-// so they pick up the post-reset module graph (importing at the top would
-// capture the stale default `WS_ROOT` before beforeAll runs).
+// `sessionFileFor` and `WS_ROOT` must be dynamic-imported inside each test so they pick up
+// the post-reset module graph (importing at the top would capture the stale default `WS_ROOT`
+// before beforeAll runs).
async function loadRouting() {
const { sessionFileFor } = await import('../../../src/main/model/core-agent/session-store');
const { WS_ROOT } = await import('../../../src/main/paths');
- return { sessionFileFor, expectDir: path.join(WS_ROOT, uid, 'cloud', 'sessions') };
+ return {
+ sessionFileFor,
+ cloudDir: path.join(WS_ROOT, uid, 'cloud', 'sessions'),
+ localDir: path.join(WS_ROOT, uid, 'local', 'sessions'),
+ };
}
describe('session-store.sessionFileFor', () => {
- it('routes gconv session to <uid>/cloud/sessions/', async () => {
- const { sessionFileFor, expectDir } = await loadRouting();
- const id = `${uid}-gconv-abcdef123456`;
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
+ it('routes gconv → <uid>/cloud/sessions/', async () => {
+ const { sessionFileFor, cloudDir } = await loadRouting();
+ const id = 'gconv-abcdef123456';
+ expect(sessionFileFor(id)).toBe(path.join(cloudDir, `${id}.jsonl`));
});
- it('routes gmember session to <uid>/cloud/sessions/', async () => {
- const { sessionFileFor, expectDir } = await loadRouting();
- const id = `${uid}-gmember-cid01-agentX`;
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
+ it('routes gmember → <uid>/cloud/sessions/', async () => {
+ const { sessionFileFor, cloudDir } = await loadRouting();
+ const id = 'gmember-cid01-agentX';
+ expect(sessionFileFor(id)).toBe(path.join(cloudDir, `${id}.jsonl`));
});
- it('routes skill-edit session to <uid>/cloud/sessions/', async () => {
- const { sessionFileFor, expectDir } = await loadRouting();
- const id = `${uid}-skill-my_skill_id`;
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
+ it('routes skill-edit → <uid>/cloud/sessions/', async () => {
+ const { sessionFileFor, cloudDir } = await loadRouting();
+ const id = 'skill-my_skill_id';
+ expect(sessionFileFor(id)).toBe(path.join(cloudDir, `${id}.jsonl`));
});
- it('routes agent-edit session to <uid>/cloud/sessions/', async () => {
- const { sessionFileFor, expectDir } = await loadRouting();
- const id = `${uid}-agent-abcdef123456`;
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
+ it('routes agent-edit → <uid>/cloud/sessions/', async () => {
+ const { sessionFileFor, cloudDir } = await loadRouting();
+ const id = 'agent-abcdef123456';
+ expect(sessionFileFor(id)).toBe(path.join(cloudDir, `${id}.jsonl`));
});
- it('routes extract-img session to <uid>/cloud/sessions/', async () => {
- const { sessionFileFor, expectDir } = await loadRouting();
- const id = `${uid}-extract-img-077355b2`;
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
- });
-
- it('routes reflect / memory-extract / anon kinds (compound names ok)', async () => {
- const { sessionFileFor, expectDir } = await loadRouting();
+ it('routes ephemeral kinds (extract-img / reflect / memory-extract / anon) → <uid>/local/sessions/', async () => {
+ const { sessionFileFor, localDir } = await loadRouting();
for (const id of [
- `${uid}-reflect-abc123`,
- `${uid}-memory-extract-1234567890`,
- `${uid}-anon-12345678`,
+ 'extract-img-077355b2',
+ 'reflect-abc123',
+ 'memory-extract-1234567890',
+ 'anon-12345678',
]) {
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
+ expect(sessionFileFor(id)).toBe(path.join(localDir, `${id}.jsonl`));
}
});
- it('preserves legacy kinds (organizer / sub / conv) — content not regenerated, but reads still resolve', async () => {
- // Migration strips brand prefix but leaves legacy kinds intact so users
- // can still open old transcripts. session-store accepts them as-is.
- const { sessionFileFor, expectDir } = await loadRouting();
- for (const id of [
- `${uid}-conv-abcdef123456`,
- `${uid}-sub-parentcid01-call01`,
- `${uid}-organizer-7a5432a7`,
- `${uid}-organizer-refine-e1cc9374`,
- ]) {
- expect(sessionFileFor(id)).toBe(path.join(expectDir, `${id}.jsonl`));
- }
+ it('routes cli (devtools archive only) → <uid>/cloud/sessions/', async () => {
+ // CLI dispatch sessions don't write a real jsonl (the CLI brings its own transcript), but
+ // the id is used as the archive key and as the spill-dir anchor. Routing is still defined.
+ const { sessionFileFor, cloudDir } = await loadRouting();
+ const id = 'cli-claude-run42';
+ expect(sessionFileFor(id)).toBe(path.join(cloudDir, `${id}.jsonl`));
});
- it('REJECTS legacy brand-prefixed ids (orkas- / aiteam-)', async () => {
- // After migration these should never reach session-store; if a stale
- // call site somehow still emits one, fail loud rather than route it.
+ it('REJECTS legacy uid-prefixed ids (`<uid>-<kind>-…`)', async () => {
+ // Migration `migrateLegacySessionIds` rewrites these on activateUser; if a stale call site
+ // still emits one, fail loud — silently routing it to a wrong-shaped filename in the
+ // active user's dir would create dangling state.
const { sessionFileFor } = await loadRouting();
- expect(() => sessionFileFor(`orkas-${uid}-agent-abcdef123456`))
+ expect(() => sessionFileFor(`${uid}-gconv-abcdef123456`))
.toThrow(/invalid session id/);
- expect(() => sessionFileFor(`aiteam-${uid}-agent-abcdef123456`))
+ expect(() => sessionFileFor('D69594E0-CF31-424C-9318-30231197E3A9-gconv-abc'))
.toThrow(/invalid session id/);
});
- it('REJECTS legacy "kind-first" format (uid in second slot)', async () => {
- // Regression guard: old-style id `extract-img-<uid>-<hex>` would
- // previously route to data/extract/sessions/ via a lax regex.
+ it('REJECTS legacy brand-prefixed ids (orkas- / aiteam-)', async () => {
const { sessionFileFor } = await loadRouting();
- expect(() => sessionFileFor(`extract-img-${uid}-077355b2`))
- .toThrow(/invalid session id/);
- expect(() => sessionFileFor(`organizer-${uid}-abc123`))
+ expect(() => sessionFileFor('orkas-agent-abcdef123456'))
.toThrow(/invalid session id/);
- });
-
- it('REJECTS id for a different uid', async () => {
- const { sessionFileFor } = await loadRouting();
- expect(() => sessionFileFor('99999999-gconv-abc'))
+ expect(() => sessionFileFor('aiteam-agent-abcdef123456'))
.toThrow(/invalid session id/);
});
- it('REJECTS unrelated string', async () => {
+ it('REJECTS unrelated strings (no recognised kind keyword)', async () => {
const { sessionFileFor } = await loadRouting();
expect(() => sessionFileFor('hello-world'))
.toThrow(/invalid session id/);
+ expect(() => sessionFileFor('garbage'))
+ .toThrow(/invalid session id/);
});
- it('REJECTS missing tail after uid', async () => {
+ it('REJECTS empty string', async () => {
const { sessionFileFor } = await loadRouting();
- expect(() => sessionFileFor(`${uid}-`))
+ expect(() => sessionFileFor(''))
.toThrow(/invalid session id/);
});
});
diff --git a/test/main/model/skill-registry.test.ts b/test/main/model/skill-registry.test.ts
index 9dea9b59..962f294f 100644
--- a/test/main/model/skill-registry.test.ts
+++ b/test/main/model/skill-registry.test.ts
@@ -115,7 +115,7 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
// — `$builtin_skills_dir / $custom_skills_dir` no longer flow through the
// prompt template, so this header IS the only place the LLM learns the
// real root paths.
- it('block header carries Read pattern + resolved ROOT values + anti-prior warning', async () => {
+ it('block header carries Read pattern + resolved ROOT values', async () => {
writeSkill(builtinDir(), 'shipped', 'Shipped', 'desc-b');
writeSkill(customDir(), 'mine', 'Mine', 'desc-c');
const { getSystemPromptBlock } = await loadRegistry();
@@ -124,7 +124,6 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
expect(text).toContain(`- custom: ${path.resolve(customDir())}`);
expect(text).toContain(`- builtin: ${path.resolve(builtinDir())}`);
expect(text).toContain('Use these ROOT values verbatim');
- expect(text).toContain('training-prior');
});
it('block omits ROOT header when no skills are present (renderSkillLines short-circuits empty)', async () => {
diff --git a/test/main/util/migrate-session-ids.test.ts b/test/main/util/migrate-session-ids.test.ts
index 54fe11c5..41415aac 100644
--- a/test/main/util/migrate-session-ids.test.ts
+++ b/test/main/util/migrate-session-ids.test.ts
@@ -3,18 +3,32 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-// Migration utility strips legacy `aiteam-` / `orkas-` prefixes from session
-// jsonl filenames and stamps `<uid>/local/.migrations` so subsequent boots
-// no-op. See src/main/util/migrate-session-ids.ts and CLAUDE.md §5.
+// Migration utility strips ANY prefix segments before the kind keyword from session jsonl
+// filenames (brand prefix `aiteam-` / `orkas-`, uid prefix in either 8-digit numeric or
+// UUID-with-dashes form, even doubled prefixes), normalising every shape to `<kind>-<tail>.jsonl`
+// (CLAUDE.md §5 — uid no longer in session_id; user scoping comes from path root). Stamps
+// `<uid>/local/.migrations` so subsequent boots no-op. See src/main/util/migrate-session-ids.ts.
let tmpDir: string;
let prevWs: string | undefined;
const TEST_UID = 'u1';
-function sessionsDir(uid: string): string {
+function cloudSessionsDir(uid: string): string {
return path.join(tmpDir, uid, 'cloud', 'sessions');
}
+function localSessionsDir(uid: string): string {
+ return path.join(tmpDir, uid, 'local', 'sessions');
+}
+function chatsIndexFile(uid: string): string {
+ return path.join(tmpDir, uid, 'cloud', 'chats', '_index.json');
+}
+function agentChatMetaFile(uid: string, agentId: string): string {
+ return path.join(tmpDir, uid, 'cloud', 'chats', 'agent', agentId, 'chat.json');
+}
+function skillChatMetaFile(uid: string, skillId: string): string {
+ return path.join(tmpDir, uid, 'cloud', 'chats', 'skill', skillId, 'chat.json');
+}
function migrationsFile(uid: string): string {
return path.join(tmpDir, uid, 'local', '.migrations');
}
@@ -36,76 +50,188 @@ afterEach(() => {
});
describe('migrate-session-ids', () => {
- it('strips aiteam- / orkas- prefixes and leaves bare-format files alone', async () => {
- const dir = sessionsDir(TEST_UID);
- touch(path.join(dir, `aiteam-${TEST_UID}-agent-a1.jsonl`), 'old1');
- touch(path.join(dir, `orkas-${TEST_UID}-gconv-c1.jsonl`), 'old2');
- touch(path.join(dir, `${TEST_UID}-skill-s1.jsonl`), 'new');
+ it('strips brand prefix (aiteam- / orkas-) AND uid prefix to land at `<kind>-<tail>.jsonl`', async () => {
+ const dir = cloudSessionsDir(TEST_UID);
+ touch(path.join(dir, 'aiteam-99999999-agent-a1.jsonl'), 'old1');
+ touch(path.join(dir, 'orkas-99999999-gconv-c1.jsonl'), 'old2');
+ touch(path.join(dir, 'gconv-c2.jsonl'), 'new');
const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
const stats = migrateLegacySessionIds(TEST_UID);
- expect(stats).toEqual({ scanned: 3, renamed: 2, alreadyMigrated: 1, conflicts: 0 });
- expect(fs.existsSync(path.join(dir, `${TEST_UID}-agent-a1.jsonl`))).toBe(true);
- expect(fs.existsSync(path.join(dir, `${TEST_UID}-gconv-c1.jsonl`))).toBe(true);
- expect(fs.existsSync(path.join(dir, `${TEST_UID}-skill-s1.jsonl`))).toBe(true);
- // 老文件不应残留
- expect(fs.existsSync(path.join(dir, `aiteam-${TEST_UID}-agent-a1.jsonl`))).toBe(false);
- expect(fs.existsSync(path.join(dir, `orkas-${TEST_UID}-gconv-c1.jsonl`))).toBe(false);
- // 内容保留(rename 而非 copy+truncate)
- expect(fs.readFileSync(path.join(dir, `${TEST_UID}-agent-a1.jsonl`), 'utf8')).toBe('old1');
+ expect(stats).toEqual({ scanned: 3, renamed: 2, alreadyMigrated: 1, conflicts: 0, fieldsRewritten: 0 });
+ expect(fs.existsSync(path.join(dir, 'agent-a1.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'gconv-c1.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'gconv-c2.jsonl'))).toBe(true);
+ // Old files gone
+ expect(fs.existsSync(path.join(dir, 'aiteam-99999999-agent-a1.jsonl'))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'orkas-99999999-gconv-c1.jsonl'))).toBe(false);
+ // Content preserved (rename, not copy+truncate)
+ expect(fs.readFileSync(path.join(dir, 'agent-a1.jsonl'), 'utf8')).toBe('old1');
});
- it('preserves legacy kinds (organizer / sub / conv) — strips prefix, keeps body', async () => {
- const dir = sessionsDir(TEST_UID);
- touch(path.join(dir, `aiteam-${TEST_UID}-conv-old.jsonl`), 'c');
- touch(path.join(dir, `aiteam-${TEST_UID}-organizer-x.jsonl`), 'o');
- touch(path.join(dir, `aiteam-${TEST_UID}-sub-y.jsonl`), 's');
+ it('strips a UUID-shaped uid prefix (the bug we hit on real OAuth-issued user_ids)', async () => {
+ const dir = cloudSessionsDir(TEST_UID);
+ const UUID = 'D69594E0-CF31-424C-9318-30231197E3A9';
+ touch(path.join(dir, `${UUID}-gconv-ac5559863d42.jsonl`), 'real-archive-sample');
+ touch(path.join(dir, `${UUID}-gmember-cv1-agt-1.jsonl`), 'agent-worker');
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ const stats = migrateLegacySessionIds(TEST_UID);
+
+ expect(stats.renamed).toBe(2);
+ expect(fs.existsSync(path.join(dir, 'gconv-ac5559863d42.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'gmember-cv1-agt-1.jsonl'))).toBe(true);
+ expect(fs.readFileSync(path.join(dir, 'gconv-ac5559863d42.jsonl'), 'utf8')).toBe('real-archive-sample');
+ });
+
+ it('handles dashed kind keywords (extract-img / memory-extract) without splitting them', async () => {
+ const dir = cloudSessionsDir(TEST_UID);
+ touch(path.join(dir, '99999999-extract-img-deadbeef.jsonl'), 'a');
+ touch(path.join(dir, '99999999-memory-extract-1234.jsonl'), 'b');
const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
migrateLegacySessionIds(TEST_UID);
- expect(fs.existsSync(path.join(dir, `${TEST_UID}-conv-old.jsonl`))).toBe(true);
- expect(fs.existsSync(path.join(dir, `${TEST_UID}-organizer-x.jsonl`))).toBe(true);
- expect(fs.existsSync(path.join(dir, `${TEST_UID}-sub-y.jsonl`))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'extract-img-deadbeef.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'memory-extract-1234.jsonl'))).toBe(true);
+ });
+
+ it('preserves legacy kinds (organizer / sub / conv) — strips prefix, keeps body shape', async () => {
+ const dir = cloudSessionsDir(TEST_UID);
+ touch(path.join(dir, 'aiteam-99999999-conv-old.jsonl'), 'c');
+ touch(path.join(dir, 'orkas-99999999-organizer-x.jsonl'), 'o');
+ touch(path.join(dir, '99999999-sub-y.jsonl'), 's');
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ migrateLegacySessionIds(TEST_UID);
+
+ expect(fs.existsSync(path.join(dir, 'conv-old.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'organizer-x.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'sub-y.jsonl'))).toBe(true);
+ });
+
+ it('also scans local/sessions/ — ephemeral kinds (extract-img / reflect / anon) live there post-routing', async () => {
+ const cloudDir = cloudSessionsDir(TEST_UID);
+ const localDir = localSessionsDir(TEST_UID);
+ touch(path.join(cloudDir, 'D69594E0-CF31-424C-9318-30231197E3A9-gconv-cv1.jsonl'), 'cloud');
+ touch(path.join(localDir, 'D69594E0-CF31-424C-9318-30231197E3A9-anon-x.jsonl'), 'local');
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ const stats = migrateLegacySessionIds(TEST_UID);
+
+ expect(stats.renamed).toBe(2);
+ expect(fs.existsSync(path.join(cloudDir, 'gconv-cv1.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(localDir, 'anon-x.jsonl'))).toBe(true);
});
it('stamps .migrations and is a no-op on second invocation', async () => {
- const dir = sessionsDir(TEST_UID);
- touch(path.join(dir, `aiteam-${TEST_UID}-agent-a1.jsonl`), 'first');
+ const dir = cloudSessionsDir(TEST_UID);
+ touch(path.join(dir, '99999999-agent-a1.jsonl'), 'first');
const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
const first = migrateLegacySessionIds(TEST_UID);
expect(first.renamed).toBe(1);
expect(fs.existsSync(migrationsFile(TEST_UID))).toBe(true);
- // 第二次:加一个新的 aiteam- 文件,但因为已盖章应当被跳过
- touch(path.join(dir, `aiteam-${TEST_UID}-skill-s2.jsonl`), 'should-not-rename');
+ // Second invocation: drop a fresh legacy file but it should be skipped (tag stamped).
+ touch(path.join(dir, '99999999-skill-s2.jsonl'), 'should-not-rename');
const second = migrateLegacySessionIds(TEST_UID);
- expect(second).toEqual({ scanned: 0, renamed: 0, alreadyMigrated: 0, conflicts: 0 });
- expect(fs.existsSync(path.join(dir, `aiteam-${TEST_UID}-skill-s2.jsonl`))).toBe(true);
+ expect(second).toEqual({ scanned: 0, renamed: 0, alreadyMigrated: 0, conflicts: 0, fieldsRewritten: 0 });
+ expect(fs.existsSync(path.join(dir, '99999999-skill-s2.jsonl'))).toBe(true);
});
- it('skips on conflict (target name already taken) without overwriting', async () => {
- const dir = sessionsDir(TEST_UID);
- touch(path.join(dir, `aiteam-${TEST_UID}-agent-a1.jsonl`), 'legacy');
- touch(path.join(dir, `${TEST_UID}-agent-a1.jsonl`), 'kept');
+ it('preserves the source file on conflict (target name already taken) — manual triage path', async () => {
+ const dir = cloudSessionsDir(TEST_UID);
+ touch(path.join(dir, '99999999-agent-a1.jsonl'), 'legacy');
+ touch(path.join(dir, 'agent-a1.jsonl'), 'kept');
const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
const stats = migrateLegacySessionIds(TEST_UID);
expect(stats.conflicts).toBe(1);
expect(stats.renamed).toBe(0);
- // 双方文件都在;新文件内容未被覆盖
- expect(fs.existsSync(path.join(dir, `aiteam-${TEST_UID}-agent-a1.jsonl`))).toBe(true);
- expect(fs.readFileSync(path.join(dir, `${TEST_UID}-agent-a1.jsonl`), 'utf8')).toBe('kept');
+ // Both files survive; new-format content not overwritten by legacy
+ expect(fs.existsSync(path.join(dir, '99999999-agent-a1.jsonl'))).toBe(true);
+ expect(fs.readFileSync(path.join(dir, 'agent-a1.jsonl'), 'utf8')).toBe('kept');
});
it('handles missing sessions dir (fresh uid, never had sessions) by stamping & returning zeros', async () => {
const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
const stats = migrateLegacySessionIds(TEST_UID);
- expect(stats).toEqual({ scanned: 0, renamed: 0, alreadyMigrated: 0, conflicts: 0 });
- // 仍然盖章,避免下次启动重扫
+ expect(stats).toEqual({ scanned: 0, renamed: 0, alreadyMigrated: 0, conflicts: 0, fieldsRewritten: 0 });
+ // Still stamped so we don't re-scan on every boot
expect(fs.existsSync(migrationsFile(TEST_UID))).toBe(true);
});
+
+ it('handles doubled prefix (aiteam-<uid>-<kind>-…) — single pass strips both', async () => {
+ const dir = cloudSessionsDir(TEST_UID);
+ touch(path.join(dir, 'aiteam-99999999-gconv-cv1.jsonl'), 'doubled');
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ migrateLegacySessionIds(TEST_UID);
+
+ expect(fs.existsSync(path.join(dir, 'gconv-cv1.jsonl'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'aiteam-99999999-gconv-cv1.jsonl'))).toBe(false);
+ });
+
+ // Why this matters (regression from real user data, 2026-05-15): renaming the jsonl files
+ // alone wasn't enough — `cloud/chats/_index.json` persists each conversation's session_id,
+ // and reads come through there. Without this rewrite, opening any pre-migration chat hands
+ // the old dashed session_id back to session-store, which creates a fresh dashed jsonl in
+ // the directory the migration just cleaned. The "renamed=6" log fires, then within minutes
+ // 6 dashed files reappear because the index pulled them back.
+ it('rewrites session_id field inside cloud/chats/_index.json', async () => {
+ touch(chatsIndexFile(TEST_UID), JSON.stringify([
+ { conversation_id: 'cv1', session_id: '99999999-gconv-cv1', title: 'a' },
+ { conversation_id: 'cv2', session_id: 'D69594E0-CF31-424C-9318-30231197E3A9-gconv-cv2', title: 'b' },
+ { conversation_id: 'cv3', session_id: 'gconv-cv3', title: 'already migrated' },
+ ]));
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ const stats = migrateLegacySessionIds(TEST_UID);
+
+ expect(stats.fieldsRewritten).toBe(2);
+ const after = JSON.parse(fs.readFileSync(chatsIndexFile(TEST_UID), 'utf8'));
+ expect(after[0].session_id).toBe('gconv-cv1');
+ expect(after[1].session_id).toBe('gconv-cv2');
+ expect(after[2].session_id).toBe('gconv-cv3');
+ // Other fields preserved.
+ expect(after[0].title).toBe('a');
+ expect(after[1].title).toBe('b');
+ });
+
+ it('rewrites session_id inside agent / skill chat.json edit-meta files', async () => {
+ touch(agentChatMetaFile(TEST_UID, 'a1'), JSON.stringify({
+ session_id: 'D69594E0-CF31-424C-9318-30231197E3A9-agent-a1',
+ otherField: 'kept',
+ }));
+ touch(skillChatMetaFile(TEST_UID, 's1'), JSON.stringify({
+ session_id: 'aiteam-99999999-skill-s1',
+ }));
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ const stats = migrateLegacySessionIds(TEST_UID);
+
+ expect(stats.fieldsRewritten).toBe(2);
+ const a = JSON.parse(fs.readFileSync(agentChatMetaFile(TEST_UID, 'a1'), 'utf8'));
+ expect(a.session_id).toBe('agent-a1');
+ expect(a.otherField).toBe('kept');
+ const s = JSON.parse(fs.readFileSync(skillChatMetaFile(TEST_UID, 's1'), 'utf8'));
+ expect(s.session_id).toBe('skill-s1');
+ });
+
+ it('skips chat.json files whose session_id is already in new format', async () => {
+ touch(agentChatMetaFile(TEST_UID, 'a1'), JSON.stringify({ session_id: 'agent-a1' }));
+
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ const stats = migrateLegacySessionIds(TEST_UID);
+
+ expect(stats.fieldsRewritten).toBe(0);
+ });
+
+ it('tolerates missing chats/ directory (fresh user with no conversations)', async () => {
+ const { migrateLegacySessionIds } = await import('../../../src/main/util/migrate-session-ids');
+ expect(() => migrateLegacySessionIds(TEST_UID)).not.toThrow();
+ });
});