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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat(connectors umbrella + i18n dropdown + rename uninstall + agent invalidation)
wytd35a70fc9993
diff --git a/CLAUDE.md b/CLAUDE.mdindex 318591d3..9ef7e9be 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -10,13 +10,15 @@ 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`). **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 / @modelcontextprotocol/sdk`). **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,7 +131,7 @@ PC/data/│ ├── 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└── local/ 🔒 Machine-private domain (never synced)- ├── config/ User prefs (auth-profiles / permissions / reflection-state / web-search-cache) — NEVER user-clearable+ ├── config/ User prefs (auth-profiles / 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)@@ -145,7 +147,7 @@ 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` (CAS + quota atomic on the Server side). 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.+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).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.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.@@ -155,6 +157,8 @@ PC/data/**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.+---## 5. Conversation / session isolation (core security invariant)@@ -182,20 +186,15 @@ session jsonl files land at `<uid>/cloud/sessions/<session_id>.jsonl` — they a### Group-chat architecture (`features/group_chat/`)-Members = `commander` + `user` + N `agent` actors (any agent first targeted by `dispatch_to` / `plan_set` is auto-added to the group). Each actor runs an independent worker loop, **no RPC**.+Independent worker loops, **no RPC between actors**. Any agent first targeted by `dispatch_to` / `plan_set` is auto-added to the group.-**Dispatch channels** (LLM → system control flow always goes through structured channels, consistent with the `<agent>` / `agent-input-form` style):-- Single agent → `dispatch_to({to, message})` tool (usable by both commander and agents).-- Multi-actor coordination → `plan_set({steps})` tool.-- User-sent messages → text `@<name>` is still parsed (user UX unchanged).-- **`@<name>` written into prose by commander / agents is NOT recognized as a dispatch signal** (LLM training tends to use `@` as markdown decoration; this used to mis-trigger and produced recurring bugs).-- `dispatch_to` calls only stage; the recipient worker is woken up only after the commander turn fully wraps up (avoiding races; same `pendingPlanAnnouncement` + delayed reconcile pattern as `plan_set`).+LLM dispatch only via structured channels (`dispatch_to` / `plan_set` tools); `@<name>` in commander / agent **prose** is NOT recognized as a dispatch signal — LLM training uses `@` as markdown decoration and this used to mis-trigger recurring bugs (user-typed `@<name>` is still parsed for UX). `dispatch_to` only stages — the recipient worker must not be woken before the commander turn fully wraps up, or the race that the `pendingPlanAnnouncement` + delayed-reconcile pattern was built to avoid reappears.-**Single dispatch primitive**: `bus.ts::enqueue(uid, cid, fromActorId, text, [forceTo], ...)` is the only external control-flow entry point for group_chat. `dispatch_to` / `plan_executor` / text @ (user only) / **CLI-backed agent worker turns** (their post-CLI reply still goes back through `bus.enqueue`, no shortcut) all funnel into this single enqueue. **Do not** introduce parallel enqueue functions; new dispatch paths must go through it. **`groupChat.retryStep / skipStep` are not exceptions** — they only mutate plan state, never enqueue directly; redispatch happens via `planExecutor.reconcileAfterStepTransition → dispatchReady → enqueue`.+**Single dispatch primitive**: `bus.ts::enqueue` is the only external control-flow entry point for group_chat. **Do not** introduce parallel enqueue functions. `groupChat.retryStep / skipStep` are not exceptions — they only mutate plan state; redispatch goes through `planExecutor.reconcileAfterStepTransition → dispatchReady → enqueue`.-**Plan rail (user-facing visualization)**: `<cid>/plan.json` is rendered as a sticky-top rail above `#chat-history` (renderer `modules/plan-rail.js`). The rail is the SOLE frontend display for plan state (the legacy `📋 执行计划` bubble label is just a one-line announcement, not a view of step status). Failed steps surface 重试/跳过/放弃 buttons that route to `groupChat.retryStep / skipStep / abort` IPC. Action buttons hide whenever `state.in_flight` is non-empty to avoid racing user actions against an in-progress turn. Status icon set is FIXED in `plan-rail.js::STATUS_ICON` — single source of truth, no LLM input, no backend / locale duplicates.+**Plan rail (`renderer/modules/plan-rail.js`)** is the SOLE frontend display for plan state — `STATUS_ICON` is single source of truth, no LLM input, no backend / locale duplicates. Failed-step action buttons hide while `state.in_flight` is non-empty to avoid racing user actions against an in-progress turn.-**Plan-level transient retry**: `PlanStep.transient_attempts` + `TRANSIENT_ERR_PATTERNS` (in `plan_executor.ts`) form a 2-tier retry stack with core-agent's `maxRetries=3` inner stream-level retry. Pattern matches undici `terminated` / `ECONNRESET` / `ETIMEDOUT` etc.; on hit, the failed step is folded back to `pending` + `transient_attempts++` + immediately redispatched via reconcile. Cap = `MAX_TRANSIENT_RETRIES` (2). **Never include `aborted` / `cancelled` in the pattern** — user-initiated abort must not be silently retried; the literal `'aborted by user'` string is also explicitly excluded by the guard. The plan layer only does state recovery — do NOT add sleep / backoff / socket-reconnect logic here (that's core-agent's job).+**Plan-level transient retry** (`plan_executor.ts::TRANSIENT_ERR_PATTERNS`, cap `MAX_TRANSIENT_RETRIES=2`): patterns must only match network-layer signals (undici `terminated` / `ECONNRESET` / `ETIMEDOUT` etc.). **Never include `aborted` / `cancelled`** — user-initiated abort must not be silently retried (`'aborted by user'` is also explicitly excluded). The plan layer only does state recovery — no sleep / backoff / socket-reconnect logic (that's core-agent's job).**Key constraints**:- **Visibility slice** (security invariant): agent X sees only messages where `from==X ∨ to∋X ∨ mentions∋X`; workers must go through `visibility.readSlice` and **never read the full `<cid>.jsonl`** (which would leak other actors' private context).@@ -268,6 +267,41 @@ 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.++**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 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.++**Provider client credentials**: `client_id` / `client_secret` come from `features/connectors/oauth-config.ts`, two sources 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).++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**: 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.++**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.++**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 (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.++**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.++**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.++**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.++**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.)++---+## 7. Knowledge base (contexts)`<uid>/cloud/contexts/` is the user-managed directory tree (mixed md/txt/pdf/docx/image, cloud-synced). The derived `vector.db` + its model config lock live at the machine-private mirror `<uid>/local/contexts/.kb/` — NOT cloud-synced (batch 2). See `features/{contexts, kb_indexer, vec_store, kb_vector}.ts` + `util/migrate-kb-to-local.ts` for the one-shot path migration.@@ -310,7 +344,8 @@ 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"**.-- **Not i18n-ed**: LLM prompts (`prompts/*.md` — the source language IS the prompt), logs, user content.+- **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.---@@ -383,7 +418,7 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t- 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.-- Add a new sync trigger pathway that doesn't go through the `DirtyBus` debounce. The five canonical triggers are: startup (post-marketplace reconcile), debounce-fired dirty event, manual ("立即同步" button), periodic 5-minute 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 lives in `engine.ts::GLOBAL_FLOOR_MS`; manual + before-quit bypass it intentionally — periodic respects it (a recent pass for any reason defers the next tick).+- Add a new sync trigger pathway outside the five canonical triggers (see §4 constraint 6); new dispatch must funnel through `DirtyBus` / `engine.syncNow`.- Wire a `dirty` event in a feature without calling `syncFeature.markDirty(domain, 'cloud/<rel>')` (and never with `'local/...'`, which would corrupt the local index).**Artifacts (`chat-app://`)**:@@ -418,6 +453,18 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t**Skill / agent enabled**:- Check `isAgentEnabled / isSkillEnabled` outside the 4 filter sites in §6; write disabled into spec JSON / SKILL.md frontmatter (violates "user preferences must not overwrite spec"); filter disabled inside `expandSkillClosure` early.+**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.+- 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.+- 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**:- Bypass `bus.enqueue` and write `<cid>.jsonl` or `visibility/<aid>.jsonl` directly (message routing / slicing / worker wake are bundled together).- Read full `<cid>.jsonl` from inside an agent worker (must use `visibility.readSlice`, otherwise other actors' private context leaks across).diff --git a/docs/plans/connectors.md b/docs/plans/connectors.mdnew file mode 100644index 00000000..d7227588--- /dev/null+++ b/docs/plans/connectors.md@@ -0,0 +1,434 @@+# Connectors(MCP-based)— 方案++> 状态:草稿,按 CLAUDE.md「Plan first」流程落地后实施。+> 跨项目:仅 PC(核心改动在 main + renderer + core-agent 装配点)。+> 验收后按约定**删除本文件**。++---++## 0. 决议汇总(来自前置对话)++- **不自营 MCP server**。Orkas 客户端只做 MCP host(client),不托管任何 first-party MCP server。每个 catalog entry 指向社区/官方的 MCP server(本地 stdio 子进程或远端 URL),跑通的形态都是「Orkas 拿到 access_token → 注入到 MCP server 的 env / Authorization header → MCP server 自己代表用户调 provider API」。+- **MCP 是连接器唯一形态**。不写"原生 TS Gmail handler",所有连接器都通过 MCP 协议接入。+- **全内置 catalog,不支持自定义安装**。所有连接器从 `features/connectors/catalog.ts::CONNECTOR_CATALOG` 这一份精选表里来;UI 没有"添加自定义 / 粘贴 URL"入口。+- **OAuth 是唯一鉴权方式**。砍掉 API-key / PAT 入口(一次性产品方向决议)。任何不能提供 OAuth 流程的服务不进 catalog。+- **OAuth 客户端在 PC 端**。PKCE + 临时 127.0.0.1 listener(§1 单点豁免),无 Server 中转。`client_id` / `client_secret` 来源:env var(Hosted Orkas 打包时注入)或 `<uid>/local/config/connector-oauth.json`(BYO)。+- **授权信息本地、不云同步**。所有 token / refresh_token / client_secret 都落 `<uid>/local/config/`(machine-private 目录,从设计上就不进 sync)。+- **加密落地**:`util/crypto-vault.ts` 走 PBKDF2 + AES-256-GCM,密钥派生 = uid + 编译期常量 salt。**保护级别:obfuscation-grade**——只挡同步泄露 / 日志泄露 / 肉眼浏览;不挡能跑 Orkas 代码的攻击者。**故意不用 keychain**(用户决议:保持 data 目录可移植、无 OS keystore 依赖)。同一 vault 同时包了 `auth-profiles.json`(模型 provider 凭据)。+- **连接器授权 ≠ 登录授权**。代码模块、存储文件、IPC namespace 全分离,不复用 `features/account/` 任何资源。+- **Phase 0 可装的内置(提供商已注册 OAuth App 后即可用)**:GitHub、Notion、Slack。**OAuth-pending(catalog 中但 MCP server 目标未选定)**:Google 套件、Microsoft 365、Discord。+- **指挥官默认全部已连接连接器可用**。智能体默认不带任何连接器,由用户在编辑页勾选。+- **新依赖**:`@modelcontextprotocol/sdk`(仅 main 端使用,client 模式)。++---++## 1. Motivation++Orkas 的指挥官 / 智能体当前能用的工具集是 `model/core-agent/` 内的固定一套(bash / write_file / kb_* / web_search / image-gen…)。要让它们使用 Gmail / Slack / Notion / GitHub / Drive 等第三方服务,**必须把工具集从静态变成可扩展的**。MCP 是为这件事设计的标准协议:++- 协议层标准化 → 一个 client 接一切 server+- 工具发现由 server 动态报告 → Orkas 不再需要为每个服务写代码+- 授权由 MCP server 维护方持有 → Orkas 公司不必去每个 provider 注册 OAuth App(除非自营 server)+- 长尾用户自定义直接复用同一条链路++最小可行形态:用户在「连接器」面板里安装/接入 MCP server,连接成功后该 server 的 tools 自动加入指挥官 / 选定智能体的可用工具集,LLM 可以像调 `bash` 一样直接调 `gmail_send`。++---++## 2. 架构总览++```+┌──────────────────────────────────────────────────────┐+│ Renderer (panel-connectors) │+│ - Gallery: 推荐 + 自定义入口 │+│ - 已连接列表 + 详情 + 断开 │+└──────────────────────────────────────────────────────┘+ │ window.orkas.invoke('connectors.*', …)+ ▼+┌──────────────────────────────────────────────────────┐+│ ipc/index.ts: connectors.* handlers │+└──────────────────────────────────────────────────────┘+ │+ ▼+┌──────────────────────────────────────────────────────┐+│ features/connectors/ │+│ ├─ types.ts Connector / Tool / Config shapes │+│ ├─ registry.ts <uid>/local/config/connectors.json │+│ ├─ mcp-client.ts MCP client wrapper(stdio + http)│+│ ├─ manager.ts lifecycle: connect / list / call │+│ ├─ tools-adapter.ts MCP tool → core-agent AgentTool │+│ ├─ bootstrap.ts boot + IPC binding │+│ └─ index.ts feature exports │+└──────────────────────────────────────────────────────┘+ │ tools 装配+ ▼+┌──────────────────────────────────────────────────────┐+│ model/core-agent/runner.ts::buildRunner() │+│ - 第 8 步:注入 enabled connectors 的 tools │+└──────────────────────────────────────────────────────┘+ │ runStream({ tools })+ ▼+ AgentRunner (in-process LLM tool-use loop)+ │+ ┌─────┴──────────┐+ │ Commander │+ │ Agent worker │+ └────────────────┘+```++**spawn 边界**(§1 单 spawn 入口原则):MCP stdio server 子进程的 `child_process.spawn` 必须**只**在 `features/connectors/mcp-client.ts` 内调用。`features/local_agents/` 依然是 5 个编码 CLI 的唯一 spawn 入口;二者职责完全分离(编码 CLI = 派发任务的 actor;MCP server = 工具提供方)。其他 features 模块要起 MCP server,必须通过 `connectors/manager.ts` 的接口,不直接 spawn。++---++## 3. 存储 layout++**单文件**:`<uid>/local/config/connectors.json`++```json+{+ "version": 1,+ "connections": {+ "gh-pat-default": {+ "id": "gh-pat-default",+ "display_name": "GitHub",+ "icon": "github",+ "transport": {+ "kind": "stdio",+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-github"],+ "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "<plaintext>" }+ },+ "enabled_subtools": null,+ "tools_cache": [+ { "name": "create_issue", "description": "...", "input_schema": {...} }+ ],+ "tools_cached_at": 1747200000000,+ "status": { "kind": "connected", "since": 1747200000000 },+ "created_at": "2026-05-14T...",+ "updated_at": "2026-05-14T..."+ },+ "notion-api-key": {+ "id": "notion-api-key",+ "display_name": "Notion",+ "transport": {+ "kind": "streamable-http",+ "url": "https://mcp.notion.com/mcp",+ "headers": { "Authorization": "Bearer <token>" }+ },+ ...+ }+ }+}+```++字段说明:+- `id`:连接实例 id(不是 connector 类型 id),用户可以连同一个服务的多个账号(gmail-personal + gmail-work)+- `transport`:MCP transport 描述。Phase 0 支持 `stdio` + `streamable-http`,不实现 SSE(已 deprecated)+- `enabled_subtools`:`null` = 全部启用;`string[]` = 白名单子集(上下文预算治理)+- `tools_cache` / `tools_cached_at`:list_tools 结果缓存。冷启动时先用 cache 让 UI 立即出,后台再 reconnect 拉新+- `status`:运行时态,**也持久化**(用于 UI 显示上次状态),但每次启动重新探测++**Why 单文件不分目录**:连接器不像 skill/agent 有 blob 内容(脚本 + 多个文件),只是配置 + token + tool schema 缓存。单文件 JSON 写起来事务简单,跟 `account.json` 同档。如果未来引入 marketplace-style connector packages,再拆 `<uid>/local/marketplace/connectors/<id>/`。++**敏感度**:跟 `account.json` 同档(plaintext under machine-private dir),但**这里存的是访问 MCP server 的 token,不是 provider 的 token**(provider token 由 MCP server 维护方自己存)。失效爆炸半径比 provider token 小。Phase 0 接受,Phase 1(任何 OAuth 接入之前)必上 keytar 包一层。++**path 助手**(新增到 `paths.ts`):++```ts+export const userConnectorsConfigFile = (uid: string) =>+ path.join(userLocalConfigDir(uid), 'connectors.json');+```++---++## 4. 组件设计++### 4.1 `types.ts`++```ts+export type Transport =+ | { kind: 'stdio'; command: string; args: string[]; env?: Record<string, string>; cwd?: string }+ | { kind: 'streamable-http'; url: string; headers?: Record<string, string> };++export interface ToolSchema {+ name: string; // 原始 MCP tool name+ description: string;+ input_schema: Record<string, unknown>;+}++export interface ConnectorInstance {+ id: string; // 用户连接实例 id(业务唯一)+ display_name: string;+ icon?: string; // 内置图标 key 或 emoji+ transport: Transport;+ enabled_subtools: string[] | null;+ tools_cache: ToolSchema[];+ tools_cached_at: number;+ status: ConnectorStatus;+ created_at: string;+ updated_at: string;+}++export type ConnectorStatus =+ | { kind: 'connected'; since: number }+ | { kind: 'connecting' }+ | { kind: 'disconnected' }+ | { kind: 'error'; message: string; at: number };+```++### 4.2 `registry.ts`++纯持久化层:`load(uid)` / `save(uid, state)` / `upsert(uid, instance)` / `remove(uid, id)`。+所有写都过 `util/locks` 串行化,避免并发覆盖。++### 4.3 `mcp-client.ts`++封装 `@modelcontextprotocol/sdk` 的 `Client`,提供:++```ts+export class McpConnection {+ constructor(private readonly cfg: Transport, private readonly log: Logger) {}+ async connect(): Promise<void>;+ async listTools(): Promise<ToolSchema[]>;+ async callTool(name: string, args: Record<string, unknown>): Promise<unknown>;+ async close(): Promise<void>;+ get isConnected(): boolean;+}+```++实现细节:+- **stdio**:用 SDK 的 `StdioClientTransport`,内部 `child_process.spawn`。**这里是连接器 spawn 子进程的唯一调用点**(§1 单入口)。+- **streamable-http**:用 SDK 的 `StreamableHTTPClientTransport`。+- 进程退出时(`before-quit`)批量 close 所有连接(参考 §5 group_chat 的清理模式)。+- spawn 失败 / list_tools 失败 / call_tool 异常 → 各自 `log.warn`/`log.error`,按 §10 logging 规范。++### 4.4 `manager.ts`++进程级单例,持有 `Map<connectorId, McpConnection>`。提供:++```ts+export async function bootstrap(uid: string): Promise<void>; // 启动时调用:load + reconnect all+export async function listInstances(uid: string): Promise<ConnectorInstance[]>;+export async function installInstance(uid: string, cfg: NewInstanceInput): Promise<ConnectorInstance>;+export async function removeInstance(uid: string, id: string): Promise<void>;+export async function refreshTools(uid: string, id: string): Promise<ToolSchema[]>;+export async function setEnabledSubtools(uid: string, id: string, subset: string[] | null): Promise<void>;+export async function callTool(uid: string, id: string, name: string, args: Record<string, unknown>): Promise<unknown>;+export async function shutdownAll(): Promise<void>;+```++`install` 流程:写 registry → 实例化 `McpConnection` → connect → listTools → 缓存 → 返回。任一步失败回滚 registry 写入。++### 4.5 `tools-adapter.ts`++把 `ToolSchema` 映射成 core-agent 期待的 `AgentTool` shape:++```ts+export function buildConnectorAgentTools(uid: string, instances: ConnectorInstance[]): AgentTool[] {+ return instances.flatMap(inst => {+ const allowed = inst.enabled_subtools;+ return inst.tools_cache+ .filter(t => allowed === null || allowed.includes(t.name))+ .map(t => ({+ name: `${inst.id}__${t.name}`, // 防撞前缀+ description: t.description,+ inputSchema: t.input_schema,+ execute: async (input, _ctx) => {+ const result = await callTool(uid, inst.id, t.name, input);+ return { ok: true, output: JSON.stringify(result) };+ },+ }));+ });+}+```++**Tool 命名**:`<instance_id>__<mcp_tool_name>`(双下划线分隔)。Why:MCP tool 原名可能重复(多个 server 都有 `list`),且 instance_id 本身就是用户给的(GH-personal / GH-work),二者拼起来防撞 + 用户 / LLM 阅读时能判断"哪个连接器的"。++**§3 anti-drift 妥协**:core-agent 的 `tool-catalog.ts::TOOL_CATALOG` 是静态表,MCP 工具动态无法 enumerate。处理:在 catalog 加一个 `mcp_connector` 占位条目作为类别说明,并在 catalog 头注释加上「带 `<inst>__` 前缀的工具走 connector 链路、不在本表 enumerate」。anti-drift 测试需要相应豁免前缀模式(具体改法在 §6 change list)。++### 4.6 `bootstrap.ts` + `index.ts`++- `bootstrap.ts::bootstrap()`:在 `main/index.ts` 的 `app.whenReady()` 后调用一次。读 registry → 重连所有 connections(best-effort,失败的实例 status 变 `error` 但不影响启动)。+- `before-quit` hook:调 `manager.shutdownAll()` 干净退出。+- `index.ts`:feature 公共 API re-export。++---++## 5. core-agent 集成++### 5.1 `runner.ts` 注入++在 `buildRunner()`(lines 224-322)第 7 步(caller extraTools)之后插入第 8 步:++```ts+// Step 8: connector tools (MCP-based)+const connectorTools = await loadConnectorToolsForActor({+ userId,+ agentId, // undefined = commander+});+wrappedTools.push(...connectorTools);+```++`loadConnectorToolsForActor` 在 `features/connectors/tools-adapter.ts`:+- `agentId` 为 undefined(commander)→ 取**所有 connected 实例**的 tools+- `agentId` 存在 → 读 agent.json 的 `enabled_connectors`(见 5.2),取交集+- 任一实例 `status.kind !== 'connected'` → 跳过,写 `log.warn` 但不阻塞 buildRunner++### 5.2 `agents.ts` 字段++`Agent` interface 增加:++```ts+enabled_connectors?: string[]; // undefined = legacy(不带任何连接器);[] = 显式空;非空 = 白名单+```++**三态语义**(对齐 §6 `skill_list` 已有约定):+- `undefined` → **空集合**(智能体默认不带连接器)。与 `skill_list` 的「`undefined`=不过滤=全开」语义**故意不同**:连接器是用户主动赋权的能力,默认应该收紧,避免存量 agent 一升级就拿到所有连接器+- `[]` → 显式空+- `string[]` → 白名单(instance id 集合)++**为什么和 `skill_list` 语义不同**:skill 是用户预先 curate 的能力集,给 agent 多曝光风险低;connector 携带外部副作用(发邮件、改文档),保守语义更安全。这条要在 CLAUDE.md §6 同步说明。++指挥官没有 agent.json,由 `runner.ts` 内部判断 `agentId === undefined` 走「全部 connected」路径。++### 5.3 Tool descriptions 缓存稳定性++§3 提到 KV-cache 前缀稳定性。MCP tools 进 `wrappedTools` 后,pi-ai 把 description + schema 编进 tool-use API 字段,**不进 prompt 文本**——天然不破坏 prompt 前缀缓存。tool 顺序:固定按 `instances` 数组顺序 + 每个 instance 内按 `tools_cache` 顺序;`tools_cache` 写入按 MCP `list_tools` 返回顺序保持。**不要**按字母排或按使用频率排(会让 tools 数组本身飘)。++---++## 6. 变更清单(按文件)++### 新增++- `PC/src/main/features/connectors/types.ts`+- `PC/src/main/features/connectors/registry.ts`+- `PC/src/main/features/connectors/mcp-client.ts`+- `PC/src/main/features/connectors/manager.ts`+- `PC/src/main/features/connectors/tools-adapter.ts`+- `PC/src/main/features/connectors/bootstrap.ts`+- `PC/src/main/features/connectors/index.ts`+- `PC/src/renderer/modules/connectors.js`++### 改动++- `PC/package.json`+ - dependencies 加 `@modelcontextprotocol/sdk`(具体版本 install 时定)+ - §1 allow-list 注释里点名加入++- `PC/src/main/paths.ts`+ - 加 `userConnectorsConfigFile(uid)`++- `PC/src/main/index.ts`+ - `app.whenReady()` 后 `await connectors.bootstrap(uid)`(在 `account.bootstrap()` 之后)+ - `before-quit` 调 `connectors.shutdownAll()`++- `PC/src/main/ipc/index.ts`+ - 加 channels:`connectors.list` / `connectors.install` / `connectors.remove` / `connectors.refresh` / `connectors.set_enabled_subtools` / `connectors.test_connection`++- `PC/src/main/model/core-agent/runner.ts`+ - buildRunner 装配链第 8 步注入 connector tools++- `PC/src/main/model/core-agent/tool-catalog.ts`+ - 加 `mcp_connector` 占位 entry + 头注释豁免 `<inst>__` 前缀+ - 同步 anti-drift 测试豁免规则(在 `test/main/core-agent/tool-catalog.test.ts` 或对应位置)++- `PC/src/main/features/agents.ts`+ - `Agent` interface 加 `enabled_connectors?: string[]`+ - `normalizeAgent` 默认空数组+ - `updateCustomAgent` 接收该字段++- `PC/src/renderer/index.html`+ - 第 33 行后插入 `connectors-btn`+ - 第 274 行后插入 `panel-connectors` section(grid + 详情双视图,对齐 `panel-skills`)+ - 加 `<script src="modules/connectors.js"></script>`++- `PC/src/renderer/modules/boot.js`+ - `setView` 路由加 `view === 'connectors'`+ - 按钮高亮 toggle++- `PC/src/main/locales/zh.json` + `en.json`+ - `sidebar.connectors`+ - `connectors.title` / `.empty` / `.add_custom` / `.tabs.available` / `.tabs.connected` / `.detail.*` / `.errors.*`++- `PC/CLAUDE.md`(sync items 见 §8)++### **不**改动++- `OpenSource/SyncCode/strip-rules.json`:连接器无 Server 依赖,OrkasOpen 自动可用+- `features/account/*`:完全不复用账号体系+- `features/local_agents/*`:MCP server spawn 走 connectors,不混进 CLI 派发+- 任何 prompt md:连接器 tool 通过 SDK tools 字段进 LLM,不进 prompt 文本++---++## 7. IPC contract++| channel | payload | response |+|---|---|---|+| `connectors.catalog` | `{}` | `{ ok: true, catalog: CatalogEntry[] }` |+| `connectors.list` | `{}` | `{ ok: true, instances: ConnectorInstance[] }` |+| `connectors.probe` | `{ catalog_id, fields }` | `{ ok: true, tools } \| error` |+| `connectors.install_from_catalog` | `{ catalog_id, fields }` | `{ ok: true, instance } \| error` |+| `connectors.remove` | `{ id }` | `{ ok: true, removed }` |+| `connectors.refresh` | `{ id }` | `{ ok: true, tools }` |+| `connectors.set_subtools` | `{ id, subtools: string[] \| null }` | `{ ok: true, instance }` |++UI 流程:用户在 `connectors.catalog` 返回的 catalog 卡片里点「连接」→ 渲染该 entry 的 `auth_fields[]` 表单 → 可选先调 `connectors.probe` → 调 `connectors.install_from_catalog` 落地。`probe` / `install_from_catalog` 内部都走 `apply-template.ts::applyTemplate` 把字段套进 `transport_template`(含 `env_synthesizer` 钩子处理 Notion 那种 JSON 头打包的特例)。++**没有 free-form 的 install 入口** —— `manager.installInstance` 已改为模块内部 `_installInstance`,所有公开路径都过 `installFromCatalog`。++---++## 8. CLAUDE.md sync items++实施完成后在 PC/CLAUDE.md 加 / 改:++- §1 npm 依赖 allow-list:增 `@modelcontextprotocol/sdk`+- §3 spawn 边界:补一行「`features/connectors/` is the sole spawn entry point for MCP stdio servers」+- §3 tool-catalog 说明:补 `<inst>__<tool>` 前缀豁免约定+- 新增 §6.5 或扩展 §6:Connectors(连接器)—— MCP-based、`<uid>/local/config/connectors.json`、agent.enabled_connectors 三态语义、tool 命名 `<inst>__<name>` 前缀、不进 prompt(走 SDK tools 字段)、Phase 1 才上 keytar+- §9 Don't do:+ - 不在 `features/connectors/` 外 spawn MCP server+ - 不把 connector token 写进 cloud/(machine-private)+ - 不把 connector tools 注入 prompt(破坏 KV-cache)+ - 不复用 `account.*` 的 i18n / IPC namespace+- OrkasOpen:连接器不进 strip-rules(无 Server 依赖)++---++## 9. 验证路径(Phase 0 出口)++1. `npm install` 后 `./run.sh` 启动正常,无新报错+2. 侧边栏出现「连接器」tab,进入空态显示「未安装任何连接器」+3. 点「添加自定义」→ 填入 `@modelcontextprotocol/server-filesystem` stdio 配置 + 一个允许目录 → 测试连接成功 → 看到工具列表+4. 在指挥官里输入「列出 ~/Desktop 下的文件」,LLM 调用 `<inst>__list_directory` 成功,看到正确结果+5. 重启应用,连接器自动重连,工具继续可用+6. 退出应用,无 zombie 进程(`pgrep -af server-filesystem` 应该空)+7. GitHub MCP 实例(PAT 模式):能调 `<inst>__list_repositories` 或类似 tool 拿到真实数据+8. 创建一个智能体,在编辑页勾选 GitHub 连接器→该 agent 能调,未勾选的智能体不能调++---++## 10. Phase 1+ 延后项(明确不在 Phase 0)++- **MCP authorization (OAuth) flow**:按 MCP spec 实现 Dynamic Client Registration + OAuth 2.0 + PKCE。回调走 `orkas://connectors/callback` deep link(沿用 `account/oauth_flow.ts` 的 protocol handler 模式,但**不复用代码**,新建 `features/connectors/oauth.ts`)。+- **keytar 加密**:token 包一层 AES-GCM,主密钥存 OS keychain。**OAuth 接入前必做**。+- **Marketplace 推荐列表**:从 Server 拉一个 curated 的 connectors 目录(可一键安装的 MCP server 列表),跟 marketplace skill/agent 同模式但走独立 endpoint。Phase 0 完全没有 marketplace,只有「添加自定义」。+- **Lazy tool discovery**:连接器数量上去后,暴露 meta-tool `discover_connector_tools(id, intent)` 让 LLM 按需查 tools,而不是把所有 tools 一次塞进 prompt。+- **写操作的 chat 内 confirm UI**:MCP spec 没有「读 vs 写」标注(annotations 字段是 hint),暂走「全部 auto-execute」;Phase 1 接入 MCP annotations + Orkas 现有 tool-use confirmation 通道。+- **多账号同 provider**:UI 显式支持同一服务连多个实例(gmail-personal + gmail-work),实例 id 由用户起名。Phase 0 schema 已经支持,但 UI 不重点展示。++---++## 11. 待定项 / 风险++1. **`@modelcontextprotocol/sdk` 版本兼容性**:SDK API 在快速迭代,install 时锁版本,并在 PR 描述里贴版本号。+2. **stdio server 启动开销**:每个 stdio server = 一个 Node/Python 子进程,N 个连接器 = N 个常驻进程。Phase 0 不做按需启停(首次 tool call 才 spawn),全在 bootstrap 起;用户量大时再优化。+3. **streamable-http 的健康探测**:Phase 0 不做 keepalive ping,依赖每次 callTool 的失败感知。+4. **错误传播给 LLM**:connector tool execute 失败时返回 `{ ok: false, error }`,core-agent 把 error 作为 tool result 给 LLM 看,让模型决定 retry / 切换路径。**不**把异常吃掉。+5. **Tool description 国际化**:MCP server 自己负责,Orkas 不翻译。zh 用户看到英文 description 是接受的(同 §6 skill description 早期阶段处理方式)。++---++实施按 §6 文件清单从 main 端往 renderer 推;E2E 验证按 §9 跑通后本文件删除(CLAUDE.md「Plan first」流程要求)。diff --git a/package-lock.json b/package-lock.jsonindex c7836bf1..b3cb08f7 100644--- a/package-lock.json+++ b/package-lock.json@@ -11,6 +11,7 @@"license": "MIT","dependencies": {"@mariozechner/pi-ai": "^0.73.0",+ "@modelcontextprotocol/sdk": "^1.29.0","adm-zip": "^0.5.16","async-mutex": "^0.5.0","better-sqlite3": "^12.9.0",@@ -1241,6 +1242,18 @@}}},+ "node_modules/@hono/node-server": {+ "version": "1.19.14",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",+ "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",+ "license": "MIT",+ "engines": {+ "node": ">=18.14.1"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },"node_modules/@huggingface/hub": {"version": "2.11.0","resolved": "https://registry.npmjs.org/@huggingface/hub/-/hub-2.11.0.tgz",@@ -1739,6 +1752,85 @@"zod-to-json-schema": "^3.25.0"}},+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.29.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",+ "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },"node_modules/@napi-rs/canvas": {"version": "0.1.99","resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.99.tgz",@@ -3179,6 +3271,44 @@"node": ">=10.0.0"}},+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/accepts/node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/accepts/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/adm-zip": {"version": "0.5.17","resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.17.tgz",@@ -3424,6 +3554,45 @@"integrity": "sha512-cTEHk2jLrPyi+12M3dhpEbnnPOsaZuq7C45ylbbQIiWgDFZq4UVYPEY5mlqjvsj/6gJv9qX5sa+ebDzLXT28Vw==","license": "MIT"},+ "node_modules/body-parser": {+ "version": "2.2.2",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",+ "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^1.0.5",+ "debug": "^4.4.3",+ "http-errors": "^2.0.0",+ "iconv-lite": "^0.7.0",+ "on-finished": "^2.4.1",+ "qs": "^6.14.1",+ "raw-body": "^3.0.1",+ "type-is": "^2.0.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/body-parser/node_modules/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/boolean": {"version": "3.2.0","license": "MIT"@@ -3466,6 +3635,15 @@"version": "1.0.1","license": "BSD-3-Clause"},+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/cacheable-lookup": {"version": "5.0.4","dev": true,@@ -3491,6 +3669,35 @@"node": ">=8"}},+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/call-bound": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "get-intrinsic": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/caseless": {"version": "0.12.0","resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",@@ -3594,6 +3801,28 @@"node": ">=10"}},+ "node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/convert-source-map": {"version": "2.0.0","resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",@@ -3601,11 +3830,46 @@"dev": true,"license": "MIT"},+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },"node_modules/core-util-is": {"version": "1.0.3","resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz","integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==","license": "MIT"+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }},"version": "2.15.4","integrity": "sha512-TP/iYTvKKKhRK89on9SRfSMGEw/9SFAAU8EC1kdT5Fmpx7dAwaCNM2+R2H1TSYoQt+03rwOs8QEfNkX8GOHjHQ==",@@ -3652,6 +3916,20 @@],"license": "MIT"},+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },"node_modules/dashdash": {"version": "1.14.1","resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",@@ -3790,6 +4068,15 @@"node": ">=0.4.0"}},+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/detect-libc": {"version": "2.1.2","license": "Apache-2.0",@@ -3831,6 +4118,20 @@"underscore": "^1.13.1"}},+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/ecc-jsbn": {"version": "0.1.2","resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",@@ -3848,6 +4149,12 @@"safe-buffer": "^5.0.1"}},+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },"node_modules/electron": {"version": "32.3.3","dev": true,@@ -3889,6 +4196,15 @@"license": "MIT","optional": true},+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/end-of-stream": {"version": "1.4.5","license": "MIT",@@ -3917,6 +4233,18 @@"node": ">= 0.4"}},+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/es6-error": {"version": "4.1.1","license": "MIT"@@ -3960,6 +4288,12 @@"@esbuild/win32-x64": "0.27.7"}},+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },"node_modules/escape-string-regexp": {"version": "4.0.0","license": "MIT",@@ -4024,6 +4358,36 @@"node": ">=0.10.0"}},+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.8.tgz",+ "integrity": "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/exif-parser": {"version": "0.1.12","resolved": "https://registry.npmjs.org/exif-parser/-/exif-parser-0.1.12.tgz",@@ -4044,6 +4408,107 @@"node": ">=12.0.0"}},+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.5.1",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.1.tgz",+ "integrity": "sha512-5O6KYmyJEpuPJV5hNTXKbAHWRqrzyu+OI3vUnSd2kXFubIVpG7ezpgxQy76Zo5GQZtrQBg86hF+CM/NX+cioiQ==",+ "license": "MIT",+ "dependencies": {+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/express/node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/express/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express/node_modules/qs": {+ "version": "6.15.1",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz",+ "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "side-channel": "^1.1.0"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/extend": {"version": "3.0.2","license": "MIT"@@ -4088,7 +4553,23 @@"integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==","license": "MIT"},- "node_modules/fast-xml-builder": {+ "node_modules/fast-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",+ "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/fast-xml-builder": {"version": "1.1.5","funding": [{@@ -4279,6 +4760,27 @@"version": "1.0.0","license": "MIT"},+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/find-up": {"version": "3.0.0","resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz",@@ -4324,6 +4826,24 @@"node": ">=12.20.0"}},+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/fs-constants": {"version": "1.0.0","license": "MIT"@@ -4376,6 +4896,15 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/function-bind": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/gaxios": {"version": "7.1.4","license": "Apache-2.0",@@ -4400,6 +4929,43 @@"node": ">=18"}},+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "license": "MIT",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "license": "MIT",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/get-stream": {"version": "5.2.0","dev": true,@@ -4621,11 +5187,64 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/hasown": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz",+ "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==",+ "license": "MIT",+ "dependencies": {+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/hono": {+ "version": "4.12.18",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.18.tgz",+ "integrity": "sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },"node_modules/http-cache-semantics": {"version": "4.2.0","dev": true,"license": "BSD-2-Clause"},+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/http-proxy-agent": {"version": "7.0.2","license": "MIT",@@ -4675,6 +5294,22 @@"node": ">= 14"}},+ "node_modules/iconv-lite": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/ieee754": {"version": "1.2.1","funding": [@@ -4723,12 +5358,23 @@"license": "ISC"},"node_modules/ip-address": {- "version": "10.1.0",+ "version": "10.2.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",+ "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==","license": "MIT","engines": {"node": ">= 12"}},+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/is-fullwidth-code-point": {"version": "3.0.0","resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",@@ -4748,6 +5394,12 @@"node": ">=8"}},+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },"node_modules/is-typedarray": {"version": "1.0.0","resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",@@ -4760,6 +5412,12 @@"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==","license": "MIT"},+ "node_modules/isexe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },"node_modules/isstream": {"version": "0.1.2","resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz",@@ -4804,6 +5462,15 @@"node": ">=18"}},+ "node_modules/jose": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz",+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },"node_modules/jpeg-js": {"version": "0.4.4","resolved": "https://registry.npmjs.org/jpeg-js/-/jpeg-js-0.4.4.tgz",@@ -5325,6 +5992,36 @@"node": ">=10"}},+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/mime": {"version": "3.0.0","resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",@@ -5459,6 +6156,15 @@"version": "2.0.0","license": "MIT"},+ "node_modules/negotiator": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/netmask": {"version": "2.1.1","license": "MIT",@@ -5546,6 +6252,27 @@"node": "*"}},+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/object-keys": {"version": "1.1.1","license": "MIT",@@ -5568,6 +6295,18 @@"integrity": "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==","license": "MIT"},+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/once": {"version": "1.4.0","license": "ISC",@@ -5758,6 +6497,15 @@"xml2js": "^0.5.0"}},+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/partial-json": {"version": "0.1.7","license": "MIT"@@ -5793,6 +6541,25 @@"node": ">=0.10.0"}},+ "node_modules/path-key": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/pathe": {"version": "2.0.3","resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",@@ -5865,6 +6632,15 @@"node": ">=12.13.0"}},+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },"node_modules/pkg-up": {"version": "3.1.0","resolved": "https://registry.npmjs.org/pkg-up/-/pkg-up-3.1.0.tgz",@@ -5974,6 +6750,19 @@"node": ">=12.0.0"}},+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/proxy-agent": {"version": "6.5.0","license": "MIT",@@ -6044,6 +6833,30 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/range-parser": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/rc": {"version": "1.2.8","license": "(BSD-2-Clause OR MIT OR Apache-2.0)",@@ -6189,6 +7002,22 @@"@rolldown/binding-win32-x64-msvc": "1.0.0-rc.16"}},+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/safe-buffer": {"version": "5.2.1","funding": [@@ -6233,6 +7062,57 @@"version": "1.0.0","license": "MIT"},+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/send/node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/send/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/serialize-error": {"version": "7.0.1","license": "MIT",@@ -6246,12 +7126,130 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/setimmediate": {"version": "1.0.5","resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz","integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==","license": "MIT"},+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/side-channel": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.3",+ "side-channel-list": "^1.0.0",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/siginfo": {"version": "2.0.0","dev": true,@@ -6469,6 +7467,15 @@"dev": true,"license": "MIT"},+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/string_decoder": {"version": "1.3.0","license": "MIT",@@ -6637,6 +7644,15 @@"node": ">=14.0.0"}},+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },"node_modules/token-types": {"version": "6.1.2","resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz",@@ -6721,6 +7737,62 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/content-type": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",+ "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/mime-db": {+ "version": "1.54.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/type-is/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/typebox": {"version": "1.1.38","resolved": "https://registry.npmjs.org/typebox/-/typebox-1.1.38.tgz",@@ -6777,6 +7849,15 @@"node": ">= 4.0.0"}},+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/uri-js": {"version": "4.4.1","resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",@@ -6809,6 +7890,15 @@"uuid": "bin/uuid"}},+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/verror": {"version": "1.10.0","resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",@@ -7022,6 +8112,21 @@"node": ">= 8"}},+ "node_modules/which": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },"node_modules/why-is-node-running": {"version": "2.3.0","dev": true,diff --git a/package.json b/package.jsonindex 2466023e..61f0ce6f 100644--- a/package.json+++ b/package.json@@ -35,6 +35,7 @@},"dependencies": {"@mariozechner/pi-ai": "^0.73.0",+ "@modelcontextprotocol/sdk": "^1.29.0","adm-zip": "^0.5.16","async-mutex": "^0.5.0","better-sqlite3": "^12.9.0",@@ -51,6 +52,15 @@"build": {"appId": "com.orkas.desktop","productName": "Orkas",+ "protocols": [+ {+ "name": "Orkas",+ "schemes": [+ "orkas"+ ],+ "role": "Viewer"+ }+ ],"directories": {"output": "dist"},diff --git a/run.sh b/run.shindex 1e86e7a9..1264c9cc 100755--- a/run.sh+++ b/run.sh@@ -3,9 +3,9 @@# 行为:每次运行都先 kill 旧实例,再启动新进程(前台)。## 用法(对齐 Server `env/start/{dev_,}api_start.sh` 的 profile 模式,详见 Server CLAUDE.md §7):-# ./run.sh # profile=global (默认,海外 orkas.ai)-# ./run.sh cn # profile=cn (国内 orkas.work)-# ORKAS_PROFILE=cn ./run.sh # env 风格仍兼容+# ./run.sh # profile=cn (默认,国内 orkas.work)+# ./run.sh global # profile=global (海外 orkas.ai)+# ORKAS_PROFILE=global ./run.sh # env 风格仍兼容# Profile 通过 ORKAS_PROFILE env 传给主进程,由 features/marketplace.ts::apiBase() 等读取,# 选择对应区域的 Orkas server。本地 dev 想覆盖到自己 server 的话,仍可单独设# ORKAS_API_BASE_URL=http://127.0.0.1:8888/api ./run.sh。@@ -18,8 +18,8 @@ if [ ! -f "$APP_DIR/package.json" ]; thenexit 1fi-# 优先级:位置参数 $1 > 环境变量 ORKAS_PROFILE > 默认 global-export ORKAS_PROFILE="${1:-${ORKAS_PROFILE:-global}}"+# 优先级:位置参数 $1 > 环境变量 ORKAS_PROFILE > 默认 cn(dev 本地默认国内环境)+export ORKAS_PROFILE="${1:-${ORKAS_PROFILE:-cn}}"echo "[Orkas] 启动 profile=$ORKAS_PROFILE"node "$APP_DIR/scripts/ensure-deps.cjs"diff --git a/src/main/features/agents.ts b/src/main/features/agents.tsindex b2bc38da..6556b816 100644--- a/src/main/features/agents.ts+++ b/src/main/features/agents.ts@@ -132,6 +132,12 @@ export interface Agent {* `general`). Empty string when uncategorized; required only when publishing to the* marketplace. Maintained via the create / edit dialog dropdown, NOT by the agent-edit LLM. */category: string;+ /** Connector instance ids this agent is allowed to call. Three-state intentionally **diverges**+ * from `skill_list`: `undefined` and `[]` both mean "no connectors" (collapsed to empty), only+ * `string[]` non-empty grants access. Why stricter than skill_list's "undefined = no filter":+ * connectors carry external side effects (sending emails, editing remote docs); a brand-new+ * agent must opt in explicitly. Maintained by the agent edit UI, NOT by the agent-edit LLM. */+ enabled_connectors?: string[];source: AgentSource;created_at: string;updated_at: string;@@ -168,6 +174,7 @@ interface AgentRaw {interactive?: unknown;runtime?: unknown;category?: unknown;+ enabled_connectors?: unknown;}/** Per-agent execution backend. See `Agent.runtime`. */@@ -474,6 +481,13 @@ export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSo}if (avatars.isKnownIcon(raw.icon)) agent.icon = raw.icon;if (avatars.isKnownColor(raw.color)) agent.color = raw.color;+ // enabled_connectors: only `string[]` carries through; missing / null / non-array all collapse+ // to "no connectors" (the field stays absent on the Agent object, which the runner treats as+ // empty). Filtering to safeId-ish strings keeps a malformed JSON from injecting weird ids.+ if (Array.isArray(raw.enabled_connectors)) {+ const filtered = raw.enabled_connectors.filter((v): v is string => typeof v === 'string' && v.length > 0);+ if (filtered.length) agent.enabled_connectors = filtered;+ }// interactive — tolerant boolean coerce (LLMs sometimes emit "true"/"false"// strings). Missing/malformed → undefined; downstream readers treat// undefined the same as false.@@ -532,6 +546,15 @@ let _agentListCache: AgentListCache | null = null;function _invalidateAgentListCache(): void { _agentListCache = null; }+/** 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'+ * `mtimeMs`. Local create/update/delete go through this module and call `_invalidateAgentListCache`+ * inline. But the sync engine writes (and `unlink`s) files directly under `<uid>/cloud/agents/<aid>/`,+ * which updates the AGENT dir's mtime but NOT the parent (`CUSTOM_AGENTS_DIR`). The parent's+ * mtime stays unchanged, the cache stamp stays valid, and `listAgents` returns ghosts of the+ * agents sync just deleted. The sync bridge calls this so the next `listAgents` re-scans. */+export const invalidateAgentListCache = _invalidateAgentListCache;+/** Toggle the active user's enabled override for an agent. Wrapping the* raw setter so the IPC handler stays one-line and the per-uid resolution* happens here. The disk-spec cache doesn't need invalidating (enabled is@@ -781,6 +804,12 @@ export interface UpdateAgentFields {* Authored by the create / edit dialog dropdown OR by the agent-edit LLM via the* `<category>` sub-tag (validated against `AGENT_CATEGORY_CODES` in `_parseAgentBlock`). */category?: string;+ /** Three-way update:+ * array (possibly empty) → replace (filtered to non-empty strings)+ * null → drop the field+ * omitted → untouched+ * Authored by the agent edit UI (connectors toggle list), NOT the agent-edit LLM. */+ enabled_connectors?: string[] | null;}/**@@ -893,6 +922,15 @@ export async function updateCustomAgent(data.inputs = validateAgentInputs(v);}}+ if (Object.prototype.hasOwnProperty.call(updates || {}, 'enabled_connectors')) {+ const v = (updates as { enabled_connectors?: string[] | null }).enabled_connectors;+ if (v === null) {+ delete (data as { enabled_connectors?: unknown }).enabled_connectors;+ } else if (Array.isArray(v)) {+ const ids = v.filter((s): s is string => typeof s === 'string' && s.length > 0);+ (data as { enabled_connectors?: string[] }).enabled_connectors = ids;+ }+ }if (Object.prototype.hasOwnProperty.call(updates || {}, 'icon')) {const v = (updates as any).icon;if (avatars.isKnownIcon(v)) data.icon = v;diff --git a/src/main/features/auth.ts b/src/main/features/auth.tsindex 1784bf11..702862fa 100644--- a/src/main/features/auth.ts+++ b/src/main/features/auth.ts@@ -56,6 +56,7 @@ import * as fs from 'node:fs';import { shell } from 'electron';import { userAuthProfilesFile, userLocalConfigDir } from '../paths';+import * as cryptoVault from '../util/crypto-vault';import { getActiveUserId } from './users';import {FEATURED_API_PROVIDERS,@@ -235,7 +236,16 @@ function ensureAuthDir(): void {function loadProfiles(): ProfilesFile {try {const raw = fs.readFileSync(profilesFile(), 'utf-8');- const data = JSON.parse(raw) as Partial<ProfilesFile>;+ // Decrypt when the file carries the vault magic header; otherwise treat as legacy plaintext.+ // The next saveProfiles() rewrites encrypted regardless, so plaintext is a one-shot+ // migration path — no need for a dedicated migration entry point.+ let json: string;+ try {+ json = cryptoVault.isEncryptedPayload(raw) ? cryptoVault.decrypt(getActiveUserId(), raw) : raw;+ } catch {+ json = raw;+ }+ const data = JSON.parse(json) as Partial<ProfilesFile>;if (data && typeof data === 'object' && data.profiles && typeof data.profiles === 'object') {const profiles: Record<string, StoredProfile> = {};for (const [id, p] of Object.entries(data.profiles)) {@@ -339,7 +349,13 @@ export function saveImageProfiles(list: ImageProfile[]): void {function saveProfiles(store: ProfilesFile): void {ensureAuthDir();- fs.writeFileSync(profilesFile(), JSON.stringify(store, null, 2), 'utf-8');+ const json = JSON.stringify(store, null, 2);+ const uid = getActiveUserId();+ // Encrypted at rest with the local-only crypto-vault — same blob format as connectors.json.+ // Obfuscation-grade (key derivable from uid alone, see util/crypto-vault.ts header); covers+ // the realistic threat surface (sync corner cases / logging / casual inspection).+ const out = uid ? cryptoVault.encrypt(uid, json) : json;+ fs.writeFileSync(profilesFile(), out, { encoding: 'utf-8', mode: 0o600 });}function makeProfileId(provider: string, label: string): string {diff --git a/src/main/features/chats.ts b/src/main/features/chats.tsindex 07521724..957e04ba 100644--- a/src/main/features/chats.ts+++ b/src/main/features/chats.ts@@ -19,9 +19,9 @@ import * as fsp from 'node:fs/promises';import * as path from 'node:path';import {- userChatsDir, userSessionFile, WS_ROOT,+ userChatsDir, userSessionsDir, WS_ROOT,} from '../paths';-import { evictSession } from '../model/core-agent/session-store';+import { evictSession, deleteSessionFileForUser } from '../model/core-agent/session-store';import {nowIso, genConversationId, safeId,readJson, writeJson, invalidateLineCount, readJsonl,@@ -32,7 +32,7 @@ import { t } from '../i18n';const log = createLogger('chats');import * as search from './search';import * as groupChat from './group_chat';-import { buildGconvSessionId, buildGmemberSessionId, readMembers, readState, setStatus } from './group_chat/state';+import { buildGconvSessionId, readState, setStatus } from './group_chat/state';import type { GroupMessage } from './group_chat/visibility';const CONVERSATION_INDEX_NAME = '_index.json';@@ -182,12 +182,21 @@ export interface CreateConversationOptions {* validating the projectId exists for this user — chats.ts persists it* verbatim. */projectId?: string;+ /** Optional explicit conversation id. Used when an external source already+ * Server assigned to a relayed command so iOS and PC agree on it). Must be+ * a `safeId`; if it collides with an existing conv, that conv is returned+ * unchanged. Defaults to a fresh generated id. */+ conversationId?: string;}export async function createConversation(userId: string, {- kind = 'normal', agentId = '', skillId = '', title = '', projectId = '',+ kind = 'normal', agentId = '', skillId = '', title = '', projectId = '', conversationId = '',}: CreateConversationOptions = {}): Promise<Conversation> {- const cid = genConversationId();+ if (conversationId && safeId(conversationId)) {+ const existing = await getConversation(userId, conversationId);+ if (existing) return existing;+ }+ const cid = (conversationId && safeId(conversationId)) ? conversationId : genConversationId();const conv: Conversation = {conversation_id: cid,title: title || t('chat.default_title'),@@ -219,17 +228,12 @@ export async function updateConversation(return items[i];}-/** Drop a session jsonl + its in-memory cache entry. */-async function purgeSession(userId: string, sessionId: string): Promise<void> {+/** Drop a session jsonl + its in-memory cache entry. Routes through+ * resolveSessionPath so kind (cloud vs local) is respected. */+function purgeSession(userId: string, sessionId: string): void {if (!sessionId) return;try { evictSession(sessionId); } catch { /* not in cache */ }- const f = userSessionFile(userId, sessionId);- try { await fsp.unlink(f); }- catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {- log.warn(`session unlink user=${userId} session=${sessionId}: ${(err as Error).message}`);- }- }+ deleteSessionFileForUser(userId, sessionId);}export async function deleteConversation(userId: string, cid: string): Promise<boolean> {@@ -250,14 +254,25 @@ export async function deleteConversation(userId: string, cid: string): Promise<bsearch.dropChatConversation(userId, cid);// Purge commander session + every per-agent member session.- await purgeSession(userId, removed?.session_id || buildGconvSessionId(userId, cid));+ purgeSession(userId, removed?.session_id || buildGconvSessionId(userId, 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}-`;try {- const m = await readMembers(userId, cid);- for (const a of m.actors) {- if (a.kind !== 'agent') continue;- await purgeSession(userId, buildGmemberSessionId(userId, cid, a.id));+ const names = await fsp.readdir(userSessionsDir(userId));+ for (const n of names) {+ if (!n.startsWith(gmemberPrefix) || !n.endsWith('.jsonl')) continue;+ purgeSession(userId, n.slice(0, -'.jsonl'.length));}- } catch { /* members may already be gone */ }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(`gmember sweep user=${userId} cid=${cid}: ${(err as Error).message}`);+ }+ }// Purge attachments + their extract caches.try {diff --git a/src/main/features/connectors/apply-template.ts b/src/main/features/connectors/apply-template.tsnew file mode 100644index 00000000..c4dcc80e--- /dev/null+++ b/src/main/features/connectors/apply-template.ts@@ -0,0 +1,70 @@+/**+ * Materialize a concrete `Transport` from a catalog entry's `transport_template` + an OAuth grant.+ *+ * Called at install time AND at every reconnect after a refresh so the spawned MCP server+ * always sees the *current* access_token. The template's `oauth_env_key` / `oauth_header_key` /+ * `env_synthesizer` decides how the token shows up in the spawn env.+ *+ * 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 type { CatalogEntry, OAuthGrant, Transport } from './types';++type EnvSynth = (access_token: string) => Record<string, string>;++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.+ notion_oauth_headers(access_token) {+ if (!access_token) throw new Error('notion_oauth_headers: missing access_token');+ return {+ OPENAPI_MCP_HEADERS: JSON.stringify({+ Authorization: `Bearer ${access_token}`,+ 'Notion-Version': '2022-06-28',+ }),+ };+ },+};++export function applyTemplate(entry: CatalogEntry, grant: OAuthGrant): Transport {+ if (!entry.transport_template) {+ throw new Error('connector not installable (no transport_template)');+ }+ const tpl = entry.transport_template;+ const token = grant.access_token;+ if (!token) throw new Error('OAuth grant has no access_token');+ if (tpl.kind === 'stdio') {+ let env: Record<string, string> = {};+ if (tpl.env_synthesizer) {+ const synth = _SYNTHESIZERS[tpl.env_synthesizer];+ if (!synth) throw new Error(`unknown env_synthesizer: ${tpl.env_synthesizer}`);+ env = { ...synth(token) };+ } else if (tpl.oauth_env_key) {+ env[tpl.oauth_env_key] = token;+ } else {+ throw new Error('OAuth stdio template needs either oauth_env_key or env_synthesizer');+ }+ return {+ kind: 'stdio',+ command: tpl.command,+ args: [...tpl.args],+ env,+ };+ }+ // streamable-http+ const headers: Record<string, string> = {};+ const headerName = tpl.oauth_header_key || 'Authorization';+ // Always send `Bearer` per RFC 6750 — `grant.token_type` is descriptive metadata from the+ // provider (Slack returns "bot", Notion sometimes returns "bearer" lowercase), NOT a wire+ // hint for the HTTP Authorization header. Every MCP server we target treats anything but+ // the literal "Bearer" prefix as missing/invalid token (Slack rejects "bot" with+ // `missing_token`, Notion rejected lowercase "bearer" with `invalid_token`). If we ever+ // need a non-Bearer scheme, add `oauth_header_scheme?: string` to the transport template+ // and default to Bearer.+ headers[headerName] = `Bearer ${token}`;+ return {+ kind: 'streamable-http',+ url: tpl.url,+ headers,+ };+}diff --git a/src/main/features/connectors/bootstrap.ts b/src/main/features/connectors/bootstrap.tsnew file mode 100644index 00000000..dbb3e5e4--- /dev/null+++ b/src/main/features/connectors/bootstrap.ts@@ -0,0 +1,41 @@+/**+ * Startup entry for the connectors feature. Called once from `main/index.ts` inside+ * `app.whenReady()` after the active uid is settled. Reconnects every persisted instance+ * best-effort — failures land as `status:error` on the registry but never block boot.+ *+ * Process-quit hook calls `manager.shutdownAll()` so stdio subprocesses (MCP servers) exit+ * cleanly instead of becoming zombies — symmetrical to the cleanup that `local_agents/runner.ts`+ * runs for its own spawned CLIs.+ */+import { app } from 'electron';+import * as manager from './manager';+import { createLogger } from '../../logger';++const log = createLogger('connectors');++let _bootPromise: Promise<void> | null = null;+let _quitHookInstalled = false;++async function _doBootstrap(uid: string): Promise<void> {+ try {+ await manager.bootstrap(uid);+ } catch (err) {+ log.warn('connectors bootstrap failed', { error: (err as Error).message });+ }+}++function _installQuitHook(): void {+ if (_quitHookInstalled) return;+ _quitHookInstalled = true;+ app.on('before-quit', () => {+ manager.shutdownAll().catch((err) => {+ log.warn('connectors shutdownAll failed', { error: (err as Error).message });+ });+ });+}++export function bootstrap(uid: string): Promise<void> {+ _installQuitHook();+ if (!_bootPromise) _bootPromise = _doBootstrap(uid);+ return _bootPromise;+}diff --git a/src/main/features/connectors/catalog.ts b/src/main/features/connectors/catalog.tsnew file mode 100644index 00000000..cd80534a--- /dev/null+++ b/src/main/features/connectors/catalog.ts@@ -0,0 +1,161 @@+/**+ * Built-in catalog of connector entries.+ *+ * Every entry uses OAuth 2.0 by default — desktop OAuth flow with PKCE and a temporary 127.0.0.1+ * callback listener (see `oauth.ts`). The catalog declares the provider endpoints + default+ * scopes; the actual `client_id` / `client_secret` come from `oauth-config.ts` (env-var at build+ * time for the Hosted Orkas builds, file-based BYO for OrkasOpen). An entry with no usable+ * OAuth client config is rendered "需先配置 OAuth client" in the UI (still visible, not+ * installable).+ *+ * **About the access_token → MCP server hop**: each catalog entry pairs a `transport_template`+ * (the MCP server we spawn) with `oauth_env_key` (the env var name the server reads). At install+ * + every reconnect, the manager injects the *current* access_token into that env var before+ * spawning. Refresh is lazy — checked at boot / `connectors.refresh` / when the model's tool+ * call surfaces a 401.+ */+import type { CatalogEntry } from './types';++export const CONNECTOR_CATALOG: CatalogEntry[] = [+ {+ id: 'github',+ display_name: 'GitHub',+ icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#181717" d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>',+ category: 'developer',+ description_zh: '仓库 / Issue / PR / 文件 / 代码搜索等 GitHub API。',+ description_en: 'Repositories, issues, PRs, files, code search, and the rest of the GitHub API.',+ auth_mode: 'server_bridge',+ oauth: { provider_id: 'github' },+ // Remote MCP via GitHub's hosted Streamable HTTP endpoint. We pass the user-to-server OAuth+ // token (ghu_*) as `Authorization: Bearer <token>` — `apply-template.ts::applyTemplate`+ // builds that header from `grant.token_type + grant.access_token`. Zero local install /+ // no MCP-server subprocess.+ transport_template: {+ kind: 'streamable-http',+ url: 'https://api.githubcopilot.com/mcp/',+ oauth_header_key: 'Authorization',+ },+ },+ {+ id: 'notion',+ display_name: 'Notion',+ icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#000" d="M4.459 4.208c.746.606 1.026.56 2.428.466l13.215-.793c.28 0 .047-.28-.046-.326L17.86 1.968c-.42-.326-.981-.7-2.055-.607L3.01 2.295c-.466.046-.56.28-.374.466zm.793 3.08v13.904c0 .747.373 1.027 1.214.98l14.523-.84c.841-.046.935-.56.935-1.167V6.354c0-.606-.233-.933-.748-.887l-15.177.887c-.56.047-.747.327-.747.933zm14.337.745c.093.42 0 .84-.42.888l-.7.14v10.264c-.608.327-1.168.514-1.635.514-.748 0-.935-.234-1.495-.933l-4.577-7.186v6.952L12.21 19s0 .84-1.168.84l-3.222.186c-.093-.186 0-.653.327-.746l.84-.233V9.854L7.822 9.76c-.094-.42.14-1.026.793-1.073l3.456-.233 4.764 7.279v-6.44l-1.215-.139c-.093-.514.28-.887.747-.933zM1.936 1.035l13.31-.98c1.634-.14 2.055-.047 3.082.7l4.249 2.986c.7.513.934.653.934 1.213v16.378c0 1.026-.373 1.634-1.68 1.726l-15.458.934c-.98.047-1.448-.093-1.962-.747l-3.129-4.06c-.56-.747-.793-1.306-.793-1.96V2.667c0-.839.374-1.54 1.447-1.632z"/></svg>',+ category: 'productivity',+ description_zh: '读写 Notion 页面 / 数据库 / 块,通过官方托管的 MCP server 直连。',+ description_en: 'Read and write Notion pages, databases, and blocks via the official hosted MCP server.',+ // DCR — Notion hosts an MCP-spec OAuth authorization server. No Orkas-side pre-registered+ // integration; PC self-registers at first connect via RFC 7591. See features/connectors/+ // oauth-dcr.ts. Server's only role is the HTTPS callback intermediate (no Notion-specific+ // code on Server).+ auth_mode: 'mcp_dcr',+ transport_template: {+ kind: 'streamable-http',+ url: 'https://mcp.notion.com/mcp',+ oauth_header_key: 'Authorization',+ },+ },+ {+ id: 'slack',+ display_name: 'Slack',+ icon_svg: '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#E01E5A" d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z"/><path fill="#36C5F0" d="M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z"/><path fill="#2EB67D" d="M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z"/><path fill="#ECB22E" d="M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z"/></svg>',+ category: 'communication',+ description_zh: '发消息、读频道、自动化工作区任务。',+ description_en: 'Post messages, browse channels, automate workspace tasks.',+ auth_mode: 'server_bridge',+ oauth: { provider_id: 'slack' },+ // Official Slack remote MCP (launched Feb 2026). Streamable HTTP — Slack does not support+ // SSE-based MCP connections. The `xoxb-*` bot token from `oauth.v2.access` goes through+ // `Authorization: Bearer <token>`; apply-template.ts normalizes the Slack-returned+ // `token_type: "bot"` to "Bearer" before the header is built.+ transport_template: {+ kind: 'streamable-http',+ url: 'https://mcp.slack.com/mcp',+ 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',+ },+ },+];++export function findCatalogEntry(id: string): CatalogEntry | null {+ return CONNECTOR_CATALOG.find((e) => e.id === id) || null;+}diff --git a/src/main/features/connectors/index.ts b/src/main/features/connectors/index.tsnew file mode 100644index 00000000..95783e2f--- /dev/null+++ b/src/main/features/connectors/index.ts@@ -0,0 +1,29 @@+export { bootstrap } from './bootstrap';+export {+ listInstances,+ getInstance,+ connectViaOAuth,+ removeInstance,+ refreshTools,+ setEnabledSubtools,+ callTool,+ shutdownAll,+} from './manager';+export { resolveVisibleConnectors, stringifyMcpResult } from './tools-adapter';+export { isValidInstanceId } from './registry';+export { CONNECTOR_CATALOG, findCatalogEntry } from './catalog';+export { handleCallbackUrl, cancelInFlightOAuth } from './oauth';+export { handleDcrCallbackUrl } from './oauth-dcr';+export type {+ Transport,+ StdioTransport,+ StreamableHttpTransport,+ ToolSchema,+ ConnectorStatus,+ ConnectorInstance,+ CatalogEntry,+ CatalogCategory,+ TransportTemplate,+ OAuthConfig,+ OAuthGrant,+} from './types';diff --git a/src/main/features/connectors/manager.ts b/src/main/features/connectors/manager.tsnew file mode 100644index 00000000..38bfa31d--- /dev/null+++ b/src/main/features/connectors/manager.ts@@ -0,0 +1,261 @@+/**+ * Connector manager — process-level singleton holding live MCP client connections.+ *+ * On boot: read registry, reconnect every instance best-effort (failures land as `status:error`+ * but don't block app startup). On shutdown: close all connections cleanly so stdio+ * subprocesses exit instead of leaking. Tool calls route here from the AgentRunner's tools[]+ * array via `tools-adapter.ts`.+ *+ * Every instance uses OAuth — there is no API-key path. The `connectViaOAuth` entry point runs+ * the full PKCE/browser/code-exchange flow, persists the grant, applies the catalog's transport+ * template (which substitutes the fresh access_token into env / headers), and brings the live+ * MCP connection up. Tokens are lazily refreshed at boot / refresh-tools / reconnect; mid-call+ * expiry surfaces as a tool error and the user re-clicks "刷新工具".+ */+import * as registry from './registry';+import { McpConnection } from './mcp-client';+import { findCatalogEntry } from './catalog';+import { applyTemplate } from './apply-template';+import { startOAuth, refreshIfStale } from './oauth';+import { startMcpDcrOAuth, refreshDcrIfStale } from './oauth-dcr';+import { createLogger } from '../../logger';+import type { CatalogEntry, ConnectorInstance, OAuthGrant, ToolSchema, Transport } from './types';++const log = createLogger('connectors:manager');++const _conns = new Map<string, McpConnection>();+let _bootedFor: string | null = null;++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);+ }+ // server_bridge default+ return refreshIfStale(uid, entry, inst.oauth_grant);+}++async function _resolveTransport(uid: string, inst: ConnectorInstance): Promise<{ transport: Transport; grant: OAuthGrant } | null> {+ const entry = findCatalogEntry(inst.id);+ if (!entry) {+ log.warn('catalog entry missing for instance', { id: inst.id });+ return null;+ }+ if (!inst.oauth_grant) {+ log.warn('instance has no oauth_grant', { id: inst.id });+ return null;+ }+ let grant: OAuthGrant;+ try {+ grant = await _refreshGrantIfStale(uid, entry, inst);+ } 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 };+}++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,+ 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,+ 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,+ 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,+ status: { kind: 'error', message: (err as Error).message, at: _now() },+ updated_at: _nowIso(),+ };+ await registry.upsert(uid, updated);+ return updated;+ }+}++export async function bootstrap(uid: string): Promise<void> {+ if (!uid || _bootedFor === uid) return;+ _bootedFor = uid;+ const file = registry.load(uid);+ const ids = Object.keys(file.connections);+ if (!ids.length) {+ log.info('no connectors to bootstrap');+ return;+ }+ await Promise.all(ids.map((id) => _connectAndCacheTools(uid, file.connections[id]).catch(() => {})));+ const connected = Array.from(_conns.values()).filter((c) => c.isConnected).length;+ log.info('connectors bootstrap done', { total: ids.length, connected });+}++export function listInstances(uid: string): ConnectorInstance[] {+ if (!uid) return [];+ const file = registry.load(uid);+ return Object.values(file.connections).sort((a, b) =>+ (a.display_name || a.id).localeCompare(b.display_name || b.id, undefined, {+ sensitivity: 'base',+ numeric: true,+ }),+ );+}++export function getInstance(uid: string, id: string): ConnectorInstance | null {+ if (!uid) return null;+ const file = registry.load(uid);+ return file.connections[id] || null;+}++/** Drive the full OAuth flow for a catalog entry and bring the resulting MCP connection up.+ * This is the **only** public install path — there is no free-form / API-key entry point.+ * Dispatches to server-bridge or DCR depending on `entry.auth_mode`. */+export async function connectViaOAuth(uid: string, catalogId: string): Promise<ConnectorInstance> {+ 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;+ let dcrClient: ConnectorInstance['dcr_client'];+ if (entry.auth_mode === 'mcp_dcr') {+ const result = await startMcpDcrOAuth(uid, entry);+ grant = result.grant;+ dcrClient = result.client;+ } else {+ if (!entry.oauth) throw new Error(`'${catalogId}' has no oauth config`);+ grant = await startOAuth(uid, entry);+ }+ log.info('connectViaOAuth: OAuth done; spawning MCP server', { catalog_id: catalogId });+ 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);+ if (prior) {+ try { await prior.close(); } catch { /* swallow */ }+ _conns.delete(catalogId);+ }++ const draft: ConnectorInstance = {+ id: entry.id,+ display_name: entry.display_name,+ transport,+ enabled_subtools: null,+ tools_cache: [],+ tools_cached_at: 0,+ status: { kind: 'connecting' },+ oauth_grant: grant,+ ...(dcrClient ? { dcr_client: dcrClient } : {}),+ created_at: _nowIso(),+ updated_at: _nowIso(),+ };+ await registry.upsert(uid, draft);+ return _connectAndCacheTools(uid, draft);+}++export async function removeInstance(uid: string, id: string): Promise<boolean> {+ if (!uid) return false;+ const conn = _conns.get(id);+ if (conn) {+ try { await conn.close(); } catch { /* swallow */ }+ _conns.delete(id);+ }+ return registry.remove(uid, id);+}++export async function refreshTools(uid: string, id: string): Promise<ToolSchema[]> {+ if (!uid) throw new Error('uid required');+ const inst = getInstance(uid, id);+ if (!inst) throw new Error('instance not found');+ // Force refresh-token check by tearing the live conn down and reconnecting through+ // _connectAndCacheTools (which re-resolves transport with a fresh access_token).+ const prior = _conns.get(id);+ if (prior) {+ try { await prior.close(); } catch { /* swallow */ }+ _conns.delete(id);+ }+ const updated = await _connectAndCacheTools(uid, inst);+ return updated.tools_cache;+}++export async function setEnabledSubtools(+ uid: string,+ id: string,+ subset: string[] | null,+): Promise<ConnectorInstance | null> {+ if (!uid) return null;+ return registry.update(uid, id, (cur) => ({+ ...cur,+ enabled_subtools: subset,+ updated_at: _nowIso(),+ }));+}++export async function callTool(+ uid: string,+ id: string,+ name: string,+ args: Record<string, unknown>,+): Promise<unknown> {+ if (!uid) throw new Error('uid required');+ let conn = _conns.get(id);+ 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);+ await conn.connect();+ _conns.set(id, conn);+ }+ return conn.callTool(name, args);+}++export async function shutdownAll(): Promise<void> {+ const all = Array.from(_conns.values());+ _conns.clear();+ await Promise.all(all.map((c) => c.close().catch(() => {})));+ _bootedFor = null;+}diff --git a/src/main/features/connectors/mcp-client.ts b/src/main/features/connectors/mcp-client.tsnew file mode 100644index 00000000..b3cfea5e--- /dev/null+++ b/src/main/features/connectors/mcp-client.ts@@ -0,0 +1,134 @@+/**+ * MCP client wrapper.+ *+ * Owns the underlying `@modelcontextprotocol/sdk` `Client` for one connector instance. Two+ * transports supported in Phase 0: `stdio` (local subprocess via SDK's StdioClientTransport)+ * and `streamable-http` (remote HTTP). SSE transport is intentionally not implemented — the+ * MCP spec has deprecated it in favor of streamable HTTP.+ *+ * Why this file is the sole spawn site for MCP child processes: PC/CLAUDE.md §1 calls out+ * `features/local_agents/` as the only spawn entry for coding-CLI dispatches. MCP servers are+ * a different class (tool-providing daemons, not job runners), but the same single-entry+ * discipline applies: the SDK's StdioClientTransport `spawn`s a node/python child here and+ * nowhere else under `features/connectors/`. Any other module that wants to talk to an MCP+ * server goes through `manager.ts`.+ *+ * Lazy SDK import — the SDK's package.json marks `type: module` even though it exposes CJS+ * `require` entries; `await import(...)` keeps the loader path identical regardless of which+ * resolver is active and avoids surprise top-level await issues during tsx transpile.+ */+import type { Transport, ToolSchema } from './types';+import { createLogger } from '../../logger';++const log = createLogger('connectors:mcp');++interface SdkBundle {+ Client: typeof import('@modelcontextprotocol/sdk/client/index.js').Client;+ StdioClientTransport: typeof import('@modelcontextprotocol/sdk/client/stdio.js').StdioClientTransport;+ StreamableHTTPClientTransport: typeof import('@modelcontextprotocol/sdk/client/streamableHttp.js').StreamableHTTPClientTransport;+}++let _sdk: SdkBundle | null = null;++async function _loadSdk(): Promise<SdkBundle> {+ if (_sdk) return _sdk;+ const [clientMod, stdioMod, httpMod] = await Promise.all([+ import('@modelcontextprotocol/sdk/client/index.js'),+ import('@modelcontextprotocol/sdk/client/stdio.js'),+ import('@modelcontextprotocol/sdk/client/streamableHttp.js'),+ ]);+ _sdk = {+ Client: clientMod.Client,+ StdioClientTransport: stdioMod.StdioClientTransport,+ StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,+ };+ return _sdk;+}++const CLIENT_INFO = { name: 'orkas-pc', version: '0.1.0' };++export class McpConnection {+ private _client: import('@modelcontextprotocol/sdk/client/index.js').Client | null = null;+ private _connected = false;++ constructor(private readonly id: string, private readonly transport: Transport) {}++ get isConnected(): boolean { return this._connected; }++ async connect(): Promise<void> {+ if (this._connected) return;+ const sdk = await _loadSdk();+ let transport: import('@modelcontextprotocol/sdk/shared/transport.js').Transport;+ if (this.transport.kind === 'stdio') {+ const envFull: Record<string, string> = { ...this.transport.env };+ log.info('spawning stdio MCP server', { id: this.id, command: this.transport.command, args: this.transport.args });+ transport = new sdk.StdioClientTransport({+ command: this.transport.command,+ args: this.transport.args,+ env: envFull,+ ...(this.transport.cwd ? { cwd: this.transport.cwd } : {}),+ });+ } else {+ const url = new URL(this.transport.url);+ log.info('connecting streamable-http MCP server', { id: this.id, url: this.transport.url });+ const opts: { requestInit?: { headers?: Record<string, string> } } = {};+ if (this.transport.headers && Object.keys(this.transport.headers).length) {+ opts.requestInit = { headers: this.transport.headers };+ }+ transport = new sdk.StreamableHTTPClientTransport(url, opts);+ }+ const client = new sdk.Client(CLIENT_INFO, {});+ try {+ // First-run `npx -y @modelcontextprotocol/server-github` can download ~10-30 MB; bound+ // the wait so a stuck spawn surfaces as a clear error instead of an indefinite hang.+ // 60s is generous for cold install on a slow link; warm runs finish in < 1s.+ const SPAWN_TIMEOUT_MS = 60_000;+ let to: NodeJS.Timeout | undefined;+ const timeout = new Promise<never>((_resolve, reject) => {+ to = setTimeout(() => reject(new Error('MCP connect timed out (>60s); likely npx/network is slow or the server crashed on launch')), SPAWN_TIMEOUT_MS);+ });+ try {+ await Promise.race([client.connect(transport), timeout]);+ } finally {+ if (to) clearTimeout(to);+ }+ this._client = client;+ this._connected = true;+ log.info('MCP connect ok', { id: this.id });+ } catch (err) {+ log.warn('connect failed', { id: this.id, error: (err as Error).message });+ try { await transport.close?.(); } catch { /* swallow */ }+ throw err;+ }+ }++ async listTools(): Promise<ToolSchema[]> {+ if (!this._client || !this._connected) throw new Error('not connected');+ const res = await this._client.listTools();+ return (res.tools || []).map((t) => ({+ name: t.name,+ description: typeof t.description === 'string' ? t.description : '',+ input_schema: (t.inputSchema && typeof t.inputSchema === 'object')+ ? t.inputSchema as Record<string, unknown>+ : { type: 'object', properties: {} },+ }));+ }++ async callTool(name: string, args: Record<string, unknown>): Promise<unknown> {+ if (!this._client || !this._connected) throw new Error('not connected');+ const res = await this._client.callTool({ name, arguments: args });+ return res;+ }++ async close(): Promise<void> {+ if (!this._client) return;+ try {+ await this._client.close();+ } catch (err) {+ log.warn('close failed', { id: this.id, error: (err as Error).message });+ } finally {+ this._client = null;+ this._connected = false;+ }+ }+}diff --git a/src/main/features/connectors/oauth-dcr.ts b/src/main/features/connectors/oauth-dcr.tsnew file mode 100644index 00000000..1fcce9e6--- /dev/null+++ b/src/main/features/connectors/oauth-dcr.ts@@ -0,0 +1,416 @@+/**+ * MCP-spec OAuth (Dynamic Client Registration) client.+ *+ * For providers that host their own OAuth authorization server per the MCP authorization spec+ * (Notion, Atlassian, Cloudflare suite, …). Orkas has no pre-registered OAuth App at the+ * provider — PC self-registers at first connect via DCR (RFC 7591), holds its own client_id /+ * client_secret per-instance, drives the full OAuth handshake from the PC side.+ *+ * The Server-bridge in `oauth.ts` handles a different class of providers (GitHub Copilot MCP+ * today) where Orkas registered an OAuth App and Server holds the secret. The two flows live+ * side-by-side and `manager.ts::connectViaOAuth` dispatches by `catalog.auth_mode`.+ *+ * Server's only role in the DCR path: serve `/api/connectors/oauth/dcr-callback` as a stable+ * HTTPS redirect_uri (DCR clients must declare one at registration), stash the {code, state}+ * pair under a one-time exchange_code, deep-link back to PC. The token POST is done from PC+ * directly against the provider's `token_endpoint` using the DCR-issued credentials.+ *+ * **Why not localhost listener (RFC 8252 native-app pattern)**: PC/CLAUDE.md §1 bans HTTP+ * server in main process. Server-bridge callback gets us a stable, registered HTTPS URI+ * (`orkas.ai/...`) at the cost of one additional KV roundtrip — fair trade.+ */+import * as crypto from 'node:crypto';+import { URL, URLSearchParams } from 'node:url';+import { shell } from 'electron';++import { getLanguage } from '../config';+import { createLogger } from '../../logger';+import type { CatalogEntry, DcrClientCredentials, OAuthGrant, Transport } from './types';++const log = createLogger('connectors:oauth-dcr');++const FLOW_TIMEOUT_MS = 10 * 60 * 1000;+const REFRESH_BUFFER_MS = 5 * 60 * 1000;+const CLIENT_NAME = 'Orkas';++interface PendingDcrFlow {+ catalogId: string;+ state: string; // CSRF token — match incoming deep link+ codeVerifier: string; // PKCE+ redirectUri: string;+ resource: string; // RFC 8707 canonical resource URI+ client: DcrClientCredentials;+ resolve: (out: { grant: OAuthGrant; client: DcrClientCredentials }) => void;+ reject: (err: Error) => void;+ timer: NodeJS.Timeout;+}++let _pending: PendingDcrFlow | null = null;++function _cancelPending(reason: string): void {+ if (!_pending) return;+ const p = _pending;+ _pending = null;+ clearTimeout(p.timer);+ p.reject(new Error(reason));+}++// ── Discovery + DCR ─────────────────────────────────────────────────────++interface ProtectedResourceMetadata {+ authorization_servers?: string[];+ resource?: string;+}++interface AuthServerMetadata {+ authorization_endpoint: string;+ token_endpoint: string;+ registration_endpoint?: string;+ // others not relevant here+}++/** Format `fetch` errors so the underlying cause (DNS / TLS / refused / …) surfaces in logs.+ * Node undici flattens every transport-level failure to `TypeError: fetch failed` with the+ * real reason hung off `err.cause`; logging just `err.message` loses the diagnostic. */+function _fmtFetchErr(label: string, err: unknown): Error {+ const e = err as Error & { cause?: unknown };+ const cause = e?.cause as { code?: string; errno?: string; message?: string } | undefined;+ const parts: string[] = [];+ if (label) parts.push(label);+ parts.push(e?.message || String(err));+ if (cause) {+ if (cause.code) parts.push(`code=${cause.code}`);+ if (cause.errno) parts.push(`errno=${cause.errno}`);+ if (cause.message && cause.message !== e?.message) parts.push(`cause=${cause.message}`);+ }+ return new Error(parts.join(' | '));+}++/** Fetch `<base>/.well-known/<name>`, falling back to root-level discovery if path-suffixed+ * fails (per MCP authorization spec — providers can serve discovery at either location). */+async function _fetchWellKnown<T>(mcpUrl: string, wellKnownName: string): Promise<T> {+ const url = new URL(mcpUrl);+ // Path-suffixed first (e.g. https://mcp.notion.com/mcp/.well-known/oauth-protected-resource).+ const candidates: string[] = [];+ const trimmed = url.pathname.replace(/\/+$/, '');+ if (trimmed) candidates.push(`${url.origin}${trimmed}/.well-known/${wellKnownName}`);+ candidates.push(`${url.origin}/.well-known/${wellKnownName}`);+ let lastErr: Error | null = null;+ for (const cand of candidates) {+ try {+ const r = await fetch(cand);+ if (r.ok) return await r.json() as T;+ lastErr = new Error(`${cand} → HTTP ${r.status}`);+ } catch (err) {+ lastErr = _fmtFetchErr(`${cand} fetch failed`, err);+ }+ }+ throw lastErr || new Error(`failed to fetch ${wellKnownName}`);+}++async function _discoverAuthServer(mcpUrl: string): Promise<{ meta: AuthServerMetadata; resource: string }> {+ const prm = await _fetchWellKnown<ProtectedResourceMetadata>(mcpUrl, 'oauth-protected-resource');+ const authServer = prm.authorization_servers?.[0];+ if (!authServer) throw new Error('protected resource metadata missing authorization_servers');+ // RFC 8707 resource indicator — the canonical resource URI from PRM. Required by the MCP+ // authorization spec on every authorize / token / refresh request, otherwise the issued+ // access_token isn't audience-bound to this MCP server and the server rejects it with+ // `invalid_token` at the first protected request. PRM is authoritative; fall back to+ // mcpUrl origin only when PRM omits the field (shouldn't happen per spec).+ const resource = prm.resource || new URL(mcpUrl).origin;+ const asUrl = new URL('/.well-known/oauth-authorization-server', authServer).toString();+ let r: Response;+ try {+ r = await fetch(asUrl);+ } catch (err) {+ throw _fmtFetchErr(`${asUrl} fetch failed`, err);+ }+ if (!r.ok) throw new Error(`auth server metadata HTTP ${r.status}`);+ const meta = await r.json() as AuthServerMetadata;+ return { meta, resource };+}++async function _registerClient(+ registrationEndpoint: string,+ redirectUri: string,+): Promise<{ client_id: string; client_secret?: string }> {+ let r: Response;+ try {+ r = await fetch(registrationEndpoint, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },+ body: JSON.stringify({+ client_name: CLIENT_NAME,+ redirect_uris: [redirectUri],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ token_endpoint_auth_method: 'client_secret_post',+ }),+ });+ } catch (err) {+ throw _fmtFetchErr(`${registrationEndpoint} fetch failed`, err);+ }+ if (!r.ok) {+ const text = await r.text();+ throw new Error(`DCR registration failed: ${r.status} ${text}`);+ }+ return await r.json() as { client_id: string; client_secret?: string };+}++// ── PKCE ───────────────────────────────────────────────────────────────++function _b64url(buf: Buffer): string {+ return buf.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');+}++function _genPkce(): { verifier: string; challenge: string } {+ const verifier = _b64url(crypto.randomBytes(32));+ const challenge = _b64url(crypto.createHash('sha256').update(verifier).digest());+ return { verifier, challenge };+}++// ── Public API ─────────────────────────────────────────────────────────++/** Run the full DCR + OAuth flow. Returns the resulting grant **and** the DCR client+ * credentials (caller must persist these — refresh uses them). */+export async function startMcpDcrOAuth(+ _uid: string,+ entry: CatalogEntry,+): Promise<{ grant: OAuthGrant; client: DcrClientCredentials }> {+ if (!entry.transport_template || entry.transport_template.kind !== 'streamable-http') {+ throw new Error('DCR flow only supports streamable-http transports');+ }+ _cancelPending('superseded by a new DCR start');++ const mcpUrl = entry.transport_template.url;+ log.info('DCR flow starting', { catalog_id: entry.id, mcp_url: mcpUrl });++ // Discover endpoints.+ const { meta, resource } = await _discoverAuthServer(mcpUrl);+ if (!meta.registration_endpoint) {+ throw new Error(`provider ${entry.id} does not advertise registration_endpoint — DCR unsupported`);+ }+ log.info('DCR endpoints discovered', {+ auth_url: meta.authorization_endpoint,+ token_url: meta.token_endpoint,+ reg_url: meta.registration_endpoint,+ resource,+ });++ // Register client. The redirect_uri must point at our Server's `/connectors/oauth/dcr-callback`+ // endpoint, which is environment-dependent (`accountApiBase()` resolves to the dev or prod+ // Server URL per `OAUTH_REDIRECT_BASE` / debug-mode rules). DCR registers whichever URL we+ // declare with the provider, so dev (127.0.0.1) and prod (orkas.ai) just work side-by-side+ // — each ConnectorInstance carries its own dcr_client tied to whichever env it was installed+ // under. (A dev-mode install does NOT migrate to prod automatically; the user would+ // reconnect.)+ const redirectUri = `${accountApiBase().replace(/\/+$/, '')}/connectors/oauth/dcr-callback`;+ const registered = await _registerClient(meta.registration_endpoint, redirectUri);+ log.info('DCR registration done', { client_id_tail: registered.client_id.slice(-6) });++ const dcrClient: DcrClientCredentials = {+ client_id: registered.client_id,+ ...(registered.client_secret ? { client_secret: registered.client_secret } : {}),+ authorization_endpoint: meta.authorization_endpoint,+ token_endpoint: meta.token_endpoint,+ registration_endpoint: meta.registration_endpoint,+ resource,+ };++ // Build authorize URL.+ const state = _b64url(crypto.randomBytes(16));+ const pkce = _genPkce();+ const authUrl = new URL(meta.authorization_endpoint);+ authUrl.searchParams.set('response_type', 'code');+ authUrl.searchParams.set('client_id', registered.client_id);+ authUrl.searchParams.set('redirect_uri', redirectUri);+ authUrl.searchParams.set('state', state);+ authUrl.searchParams.set('code_challenge', pkce.challenge);+ authUrl.searchParams.set('code_challenge_method', 'S256');+ authUrl.searchParams.set('resource', resource);++ log.info('opening DCR authorize URL', { catalog_id: entry.id });++ return new Promise<{ grant: OAuthGrant; client: DcrClientCredentials }>((resolve, reject) => {+ const timer = setTimeout(() => _cancelPending('DCR flow timed out'), FLOW_TIMEOUT_MS);+ timer.unref?.();+ _pending = {+ catalogId: entry.id,+ state,+ codeVerifier: pkce.verifier,+ redirectUri,+ resource,+ client: dcrClient,+ resolve,+ reject,+ timer,+ };+ shell.openExternal(authUrl.toString()).catch((err) => {+ _cancelPending(`failed to open browser: ${(err as Error).message}`);+ });+ });+}++/** Called by the protocol handler when `orkas://connectors/oauth/dcr-callback?...` arrives. */+export async function handleDcrCallbackUrl(rawUrl: string): Promise<void> {+ log.info('DCR callback url received', { path: rawUrl.split('?')[0] });+ if (!_pending) {+ log.warn('DCR callback arrived with no pending flow');+ return;+ }+ const pending = _pending;+ let url: URL;+ try { url = new URL(rawUrl); } catch (err) {+ _cancelPending(`malformed DCR callback: ${(err as Error).message}`);+ return;+ }+ const status = url.searchParams.get('status');+ const reason = url.searchParams.get('reason') || '';+ if (status === 'cancelled') { _cancelPending('user cancelled at provider'); return; }+ if (status === 'error') { _cancelPending(`server error: ${reason || 'unknown'}`); return; }+ const exchangeCode = url.searchParams.get('exchange_code');+ if (!exchangeCode) { _cancelPending('missing exchange_code'); return; }++ // Pull {oauth_code, oauth_state} from Server. Server uses the namespaced keys (not bare+ // `code`/`state`) because `json_response` spreads data flat — a bare `code` key would+ // collide with the response status `code` field. See Server `api/connectors.py` comment.+ let payload: { code: string; state: string };+ try {+ const res = await fetch(`${accountApiBase()}/connectors/oauth/dcr-exchange`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ },+ body: JSON.stringify({ exchange_code: exchangeCode, device_id: tokenStore.getDeviceId() }),+ });+ if (!res.ok) throw new Error(`/dcr-exchange HTTP ${res.status}`);+ const body = await res.json() as {+ code: number; // status — 0 = ok+ msg?: string;+ oauth_code?: string;+ oauth_state?: string;+ };+ if (body.code !== 0 || !body.oauth_code || !body.oauth_state) {+ throw new Error(body.msg || 'dcr exchange response invalid');+ }+ payload = { code: body.oauth_code, state: body.oauth_state };+ } catch (err) {+ _cancelPending(`dcr exchange failed: ${_fmtFetchErr('', err).message}`);+ return;+ }++ // Validate state.+ if (payload.state !== pending.state) {+ _cancelPending('state mismatch (CSRF guard)');+ return;+ }++ // Exchange code for tokens against provider's token endpoint.+ try {+ const body = new URLSearchParams({+ grant_type: 'authorization_code',+ code: payload.code,+ redirect_uri: pending.redirectUri,+ client_id: pending.client.client_id,+ code_verifier: pending.codeVerifier,+ resource: pending.resource,+ });+ if (pending.client.client_secret) body.set('client_secret', pending.client.client_secret);+ const res = await fetch(pending.client.token_endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Accept: 'application/json',+ },+ body: body.toString(),+ });+ if (!res.ok) {+ const text = await res.text();+ throw new Error(`token endpoint HTTP ${res.status}: ${text}`);+ }+ const tokens = await res.json() as {+ access_token: string;+ refresh_token?: string;+ expires_in?: number;+ token_type?: string;+ scope?: string;+ };+ if (!tokens.access_token) throw new Error('token response missing access_token');+ const expires_at = typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : null;+ const grant: OAuthGrant = {+ access_token: tokens.access_token,+ refresh_token: tokens.refresh_token || null,+ expires_at,+ scopes: tokens.scope ? tokens.scope.split(/[\s,]+/).filter(Boolean) : [],+ token_type: tokens.token_type || 'Bearer',+ };+ _pending = null;+ clearTimeout(pending.timer);+ log.info('DCR grant resolved', {+ catalog_id: pending.catalogId,+ has_refresh: !!grant.refresh_token,+ expires_in: tokens.expires_in ?? null,+ });+ pending.resolve({ grant, client: pending.client });+ } catch (err) {+ _cancelPending(`token exchange failed: ${_fmtFetchErr('', err).message}`);+ }+}++/** Refresh a DCR-issued access_token. Called by manager before reconnect when expires_at is+ * near. */+export async function refreshDcrIfStale(+ client: DcrClientCredentials,+ grant: OAuthGrant,+): Promise<OAuthGrant> {+ if (!grant.expires_at) return grant;+ if (grant.expires_at - Date.now() > REFRESH_BUFFER_MS) return grant;+ if (!grant.refresh_token) {+ throw new Error('access_token expired and no refresh_token available; reconnect required');+ }+ const body = new URLSearchParams({+ grant_type: 'refresh_token',+ refresh_token: grant.refresh_token,+ client_id: client.client_id,+ });+ if (client.resource) body.set('resource', client.resource);+ if (client.client_secret) body.set('client_secret', client.client_secret);+ let res: Response;+ try {+ res = await fetch(client.token_endpoint, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ Accept: 'application/json',+ },+ body: body.toString(),+ });+ } catch (err) {+ throw _fmtFetchErr(`${client.token_endpoint} fetch failed`, err);+ }+ if (!res.ok) {+ const text = await res.text();+ throw new Error(`DCR refresh HTTP ${res.status}: ${text}`);+ }+ const tokens = await res.json() as {+ access_token: string;+ refresh_token?: string;+ expires_in?: number;+ token_type?: string;+ scope?: string;+ };+ if (!tokens.access_token) throw new Error('DCR refresh response missing access_token');+ const expires_at = typeof tokens.expires_in === 'number' ? Date.now() + tokens.expires_in * 1000 : null;+ return {+ access_token: tokens.access_token,+ // Notion (and others) rotate refresh_token on every refresh — using the old one again+ // invalidates the new. Replace if the response carries a new one; fall back to the prior+ // only when the server omitted it (some providers do that for non-rotating refresh).+ refresh_token: tokens.refresh_token || grant.refresh_token,+ expires_at,+ scopes: tokens.scope ? tokens.scope.split(/[\s,]+/).filter(Boolean) : grant.scopes,+ token_type: tokens.token_type || grant.token_type || 'Bearer',+ ...(grant.account_label ? { account_label: grant.account_label } : {}),+ };+}diff --git a/src/main/features/connectors/oauth.ts b/src/main/features/connectors/oauth.tsnew file mode 100644index 00000000..3598f935--- /dev/null+++ b/src/main/features/connectors/oauth.ts@@ -0,0 +1,223 @@+/**+ * Connector OAuth — Server-bridge flow (mirror of `features/account/oauth_flow.ts`).+ *+ * Flow:+ * 1. PC `startOAuth(catalog_id)` → opens system browser to+ * `<accountApiBase>/connectors/oauth/<provider>/start?d=<device_id>&lang=<lang>`+ * 2. Server picks `client_id` / `client_secret` (Orkas-registered OAuth App; **NOT** in PC+ * binary), redirects browser through the provider consent screen.+ * 3. Provider callback lands on the Server's `<base>/connectors/oauth/<provider>/callback`,+ * Server runs the token exchange, stores `{provider, tokens}` against a one-time+ * `exchange_code` (short TTL, `device_id`-bound), 302s the browser through a landing page+ * that deep-links `orkas://connectors/oauth/callback?exchange_code=...`.+ * 4. PC's protocol handler routes the deep link here → POST+ * `<base>/connectors/oauth/exchange` → gets `{provider, access_token, refresh_token,+ * expires_in, scopes, account_label}` → persists locally (encrypted via crypto-vault) →+ * brings the MCP connection up.+ *+ * Token data NEVER persists on Server beyond `EXCHANGE_TTL`. Refresh is handled client-side+ * via the provider's standard refresh_token grant (`refreshIfStale`).+ *+ * **No localhost HTTP listener** — §1 hard rule. The earlier draft of this file bound an+ * ephemeral 127.0.0.1 port; that approach was scrapped in favor of the existing `orkas://`+ * deep-link infrastructure (same as account login). Don't bring the listener back.+ */+import { shell } from 'electron';++import { getLanguage } from '../config';+import { createLogger } from '../../logger';+import type { CatalogEntry, OAuthGrant } from './types';++const log = createLogger('connectors:oauth');++// 10 minutes — comfortably covers a slow provider consent screen + 2FA. The Server side enforces+// its own short TTLs on state / exchange_code (see Server/biz/connectors/oauth_flow_mgr.py).+const FLOW_TIMEOUT_MS = 10 * 60 * 1000;+const REFRESH_BUFFER_MS = 5 * 60 * 1000;++interface PendingFlow {+ catalogId: string;+ resolve: (grant: OAuthGrant) => void;+ reject: (err: Error) => void;+ timer: NodeJS.Timeout;+}++// At most one connector OAuth flow in flight per app instance. The protocol handler reads from+// this to fulfill the right Promise when the deep link arrives.+let _pending: PendingFlow | null = null;++function _cancelPending(reason: string): void {+ if (!_pending) return;+ const p = _pending;+ _pending = null;+ clearTimeout(p.timer);+ p.reject(new Error(reason));+}++/** Externally callable cancel — wired to the renderer's "取消" link so a user who closed the+ * browser without completing OAuth can unfreeze the card without waiting for the timeout. */+export function cancelInFlightOAuth(): boolean {+ if (!_pending) return false;+ _cancelPending('cancelled by user');+ return true;+}++/** Drive the full OAuth flow for a catalog entry. Resolves with the OAuthGrant or rejects. */+export async function startOAuth(_uid: string, entry: CatalogEntry): Promise<OAuthGrant> {+ if (!entry.oauth) throw new Error(`catalog entry ${entry.id} has no oauth config`);+ // Pre-empt any prior in-flight flow — the user clicking another card while one is open is a+ // legitimate UX path (cancel the old one and start over).+ _cancelPending('superseded by a new OAuth start');++ const providerId = entry.oauth.provider_id;+ const startUrl = new URL(`${accountApiBase()}/connectors/oauth/${encodeURIComponent(providerId)}/start`);+ startUrl.searchParams.set('d', tokenStore.getDeviceId());+ startUrl.searchParams.set('lang', getLanguage());+ startUrl.searchParams.set('catalog_id', entry.id);++ log.info('opening connector OAuth start url', { provider: providerId, catalog_id: entry.id });+ return new Promise<OAuthGrant>((resolve, reject) => {+ const timer = setTimeout(() => {+ _cancelPending('OAuth flow timed out');+ }, FLOW_TIMEOUT_MS);+ timer.unref?.();+ _pending = { catalogId: entry.id, resolve, reject, timer };+ shell.openExternal(startUrl.toString()).catch((err) => {+ _cancelPending(`failed to open browser: ${(err as Error).message}`);+ });+ });+}++/** Called by the protocol handler when `orkas://connectors/oauth/callback?...` arrives. */+export async function handleCallbackUrl(rawUrl: string): Promise<void> {+ log.info('connector callback url received', { path: rawUrl.split('?')[0] });+ if (!_pending) {+ log.warn('connector callback arrived with no pending flow', { url: rawUrl.split('?')[0] });+ return;+ }+ const pending = _pending;+ let url: URL;+ try { url = new URL(rawUrl); }+ catch (err) {+ _cancelPending(`malformed callback URL: ${(err as Error).message}`);+ return;+ }+ void pending;+ const status = url.searchParams.get('status');+ const reason = url.searchParams.get('reason') || '';+ if (status === 'cancelled') { _cancelPending('user cancelled at provider'); return; }+ if (status === 'error') { _cancelPending(`server error: ${reason || 'unknown'}`); return; }+ const exchangeCode = url.searchParams.get('exchange_code');+ if (!exchangeCode) { _cancelPending('missing exchange_code'); return; }++ try {+ const res = await fetch(`${accountApiBase()}/connectors/oauth/exchange`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ ...tokenStore.authHeaders(),+ },+ body: JSON.stringify({+ exchange_code: exchangeCode,+ device_id: tokenStore.getDeviceId(),+ }),+ });+ if (!res.ok) {+ const text = await res.text();+ throw new Error(`exchange HTTP ${res.status}: ${text}`);+ }+ // Server's `api/response.py::json_response(code, msg, data)` **spreads** the data dict into+ // the top-level body (see Web/CLAUDE.md §3 "Read res.code, not res.data.code"); the payload+ // fields hang directly off the body, NOT under a nested `data` key.+ const body = await res.json() as {+ code: number;+ msg?: string;+ provider?: string;+ access_token?: string;+ refresh_token?: string;+ expires_in?: number;+ token_type?: string;+ scope?: string;+ account_label?: string;+ };+ if (body.code !== 0 || !body.access_token) {+ throw new Error(body.msg || 'invalid exchange response');+ }+ const expires_at = typeof body.expires_in === 'number' ? Date.now() + body.expires_in * 1000 : null;+ const scopes = body.scope ? body.scope.split(/[\s,]+/).filter(Boolean) : [];+ const grant: OAuthGrant = {+ access_token: body.access_token,+ refresh_token: body.refresh_token || null,+ expires_at,+ scopes,+ token_type: body.token_type || 'Bearer',+ ...(body.account_label ? { account_label: body.account_label } : {}),+ };+ _pending = null;+ clearTimeout(pending.timer);+ log.info('connector OAuth grant resolved', {+ catalog_id: pending.catalogId,+ has_refresh: !!grant.refresh_token,+ expires_in: typeof body.expires_in === 'number' ? body.expires_in : null,+ account_label: grant.account_label || null,+ });+ pending.resolve(grant);+ } catch (err) {+ log.warn('connector OAuth exchange failed', { error: (err as Error).message });+ _cancelPending(`exchange failed: ${(err as Error).message}`);+ }+}++/** Refresh the access_token if it's expired or about to expire. Calls the provider directly+ * through the Server's refresh proxy. */+export async function refreshIfStale(uid: string, entry: CatalogEntry, grant: OAuthGrant): Promise<OAuthGrant> {+ if (!grant.expires_at) return grant;+ if (grant.expires_at - Date.now() > REFRESH_BUFFER_MS) return grant;+ if (!grant.refresh_token) {+ throw new Error('access_token expired and no refresh_token available; reconnect required');+ }+ if (!entry.oauth) throw new Error('no oauth config');+ const res = await fetch(`${accountApiBase()}/connectors/oauth/refresh`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ ...tokenStore.authHeaders(),+ },+ body: JSON.stringify({+ provider: entry.oauth.provider_id,+ refresh_token: grant.refresh_token,+ device_id: tokenStore.getDeviceId(),+ }),+ });+ if (!res.ok) {+ const text = await res.text();+ throw new Error(`refresh HTTP ${res.status}: ${text}`);+ }+ // Same flat shape as the exchange endpoint — see comment above.+ const body = await res.json() as {+ code: number;+ msg?: string;+ access_token?: string;+ refresh_token?: string;+ expires_in?: number;+ token_type?: string;+ scope?: string;+ };+ if (body.code !== 0 || !body.access_token) {+ throw new Error(body.msg || 'invalid refresh response');+ }+ const expires_at = typeof body.expires_in === 'number' ? Date.now() + body.expires_in * 1000 : null;+ const scopes = body.scope ? body.scope.split(/[\s,]+/).filter(Boolean) : grant.scopes;+ void uid;+ const next: OAuthGrant = {+ access_token: body.access_token,+ refresh_token: body.refresh_token || grant.refresh_token,+ expires_at,+ scopes,+ token_type: body.token_type || 'Bearer',+ ...(grant.account_label ? { account_label: grant.account_label } : {}),+ };+ return next;+}diff --git a/src/main/features/connectors/registry.ts b/src/main/features/connectors/registry.tsnew file mode 100644index 00000000..30c0c98f--- /dev/null+++ b/src/main/features/connectors/registry.ts@@ -0,0 +1,112 @@+/**+ * 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.+ *+ * 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.+ *+ * All writes are serialized via async-mutex so two concurrent IPC calls can't race-overwrite.+ */+import * as fs from 'node:fs';+import { Mutex } from 'async-mutex';++import { userConnectorsConfigFile, userLocalConfigDir } from '../../paths';+import { createLogger } from '../../logger';+import * as cryptoVault from '../../util/crypto-vault';+import type { ConnectorInstance, ConnectorsFile } from './types';++const log = createLogger('connectors:registry');+const _writeMutex = new Mutex();++const EMPTY: ConnectorsFile = { version: 1, connections: {} };++function _readSync(uid: string): ConnectorsFile {+ const file = userConnectorsConfigFile(uid);+ let raw: string;+ try {+ raw = fs.readFileSync(file, 'utf8');+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT') {+ log.warn('reading connectors.json failed', { error: (err as Error).message });+ }+ 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 });+ 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 failed', { error: (err as Error).message });+ }+ return { version: 1, connections: {} };+}++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 });+ } catch (err) {+ log.error('failed to persist connectors.json', { error: (err as Error).message });+ throw err;+ }+}++export function load(uid: string): ConnectorsFile {+ if (!uid) return EMPTY;+ return _readSync(uid);+}++export async function upsert(uid: string, inst: ConnectorInstance): Promise<void> {+ await _writeMutex.runExclusive(async () => {+ const cur = _readSync(uid);+ cur.connections[inst.id] = inst;+ _writeSync(uid, cur);+ });+}++export async function remove(uid: string, id: string): Promise<boolean> {+ return _writeMutex.runExclusive(async () => {+ const cur = _readSync(uid);+ if (!cur.connections[id]) return false;+ delete cur.connections[id];+ _writeSync(uid, cur);+ return true;+ });+}++export async function update(+ uid: string,+ id: string,+ patch: (inst: ConnectorInstance) => ConnectorInstance,+): Promise<ConnectorInstance | null> {+ return _writeMutex.runExclusive(async () => {+ const cur = _readSync(uid);+ const existing = cur.connections[id];+ if (!existing) return null;+ const next = patch(existing);+ cur.connections[id] = next;+ _writeSync(uid, cur);+ return next;+ });+}++export function isValidInstanceId(id: unknown): id is string {+ return typeof id === 'string' && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(id);+}diff --git a/src/main/features/connectors/tools-adapter.ts b/src/main/features/connectors/tools-adapter.tsnew file mode 100644index 00000000..65d7b249--- /dev/null+++ b/src/main/features/connectors/tools-adapter.ts@@ -0,0 +1,81 @@+/**+ * Connector visibility resolver + MCP-result stringifier.+ *+ * Until 2026-05 this file built one `AgentTool` per connector × tool and dumped the lot into the+ * AgentRunner's `tools[]`. That hit a hard wall once users started installing 5+ connectors —+ * the model's tool-selection accuracy drops sharply past 20–50 tools (Anthropic 30–50 / Cline+ * ~20 / Cursor ~40), and connect/disconnect events invalidated the entire prompt-cache prefix.+ *+ * Connectors are now surfaced through the three umbrella meta-tools in+ * `model/core-agent/connector-meta-tools.ts` (`list_connectors` / `list_connector_tools` /+ * `call_connector_tool`). The meta-tools share `resolveVisibleConnectors` here so the actor+ * visibility matrix (commander vs. agent worker, `enabled_connectors` whitelist,+ * `enabled_subtools` instance filter) is single-sourced.+ *+ * Actor scope:+ * - `agentId === undefined` (commander) → every installed instance+ * - `agentId` present → respect `agent.enabled_connectors`. `undefined` AND `[]` BOTH mean+ * "no connectors" (intentionally stricter than `agent.skill_list`'s three-state — see+ * PC/CLAUDE.md §6.5 "Per-agent scope"). Only a non-empty `string[]` grants access.+ *+ * Disconnected instances are still returned (with their stale `tools_cache` and current status)+ * so callers can surface the situation to the user; `manager.callTool` auto-reconnects on use,+ * but `list_connector_tools` refuses to advertise schemas for a non-`connected` instance.+ */+import * as manager from './manager';+import * as agents from '../agents';+import type { ConnectorInstance, ToolSchema } from './types';++/** Convert MCP `callTool`'s raw result into a single string the LLM can read.+ * MCP result shape: `{ content: [{type, text|data, …}], isError? }`. Text parts are flattened;+ * anything else is JSON-serialised so the LLM still sees structure. Image / resource parts are+ * dropped (no multimodal in tool results yet — see plan §10 in connectors.md). */+export function stringifyMcpResult(raw: unknown): string {+ if (raw == null) return '';+ if (typeof raw === 'string') return raw;+ if (typeof raw === 'object') {+ const obj = raw as { content?: Array<{ type?: string; text?: string }> };+ if (Array.isArray(obj.content)) {+ const textParts = obj.content+ .filter((p) => p && typeof p === 'object' && p.type === 'text' && typeof p.text === 'string')+ .map((p) => p.text as string);+ if (textParts.length) return textParts.join('\n');+ }+ try { return JSON.stringify(raw); } catch { return String(raw); }+ }+ return String(raw);+}++/** Resolve the connectors visible to a given actor + the tool subset each one exposes.+ * Returns one entry per visible instance; `tools` is post-`enabled_subtools` filter. Instances+ * whose `tools_cache` is empty (e.g. cold-start before the first successful list_tools) are+ * still returned with `tools: []`. */+export async function resolveVisibleConnectors(+ uid: string,+ agentId: string | undefined,+): Promise<Array<{ instance: ConnectorInstance; tools: ToolSchema[] }>> {+ if (!uid) return [];+ const all = manager.listInstances(uid);+ if (!all.length) return [];+ const scope = await _enabledInstancesForActor(uid, agentId, all);+ return scope.map((instance) => {+ const allowed = instance.enabled_subtools;+ const tools = allowed === null+ ? instance.tools_cache+ : instance.tools_cache.filter((t) => allowed.includes(t.name));+ return { instance, tools };+ });+}++async function _enabledInstancesForActor(+ uid: string,+ agentId: string | undefined,+ allInstances: ConnectorInstance[],+): Promise<ConnectorInstance[]> {+ if (!agentId) return allInstances;+ const agent = await agents.getAgent(agentId);+ const allowed = agent?.enabled_connectors;+ if (!Array.isArray(allowed) || allowed.length === 0) return [];+ const allowSet = new Set(allowed);+ return allInstances.filter((i) => allowSet.has(i.id));+}diff --git a/src/main/features/connectors/types.ts b/src/main/features/connectors/types.tsnew file mode 100644index 00000000..c5699990--- /dev/null+++ b/src/main/features/connectors/types.ts@@ -0,0 +1,198 @@+/**+ * Connector types (MCP-based).+ *+ * A connector instance = one configured MCP server connection. Same service can have multiple+ * instances (gmail-personal + gmail-work) with distinct ids. Tool calls flow through the MCP+ * client manager (`manager.ts`); the tool schema cache lives on the instance so the LLM tools[]+ * array can be assembled without waiting on a live server (cold-start instances surface a stale+ * cache; reconcile happens on first successful reconnect).+ */++export type Transport =+ | StdioTransport+ | StreamableHttpTransport;++export interface StdioTransport {+ kind: 'stdio';+ command: string;+ args: string[];+ env?: Record<string, string>;+ cwd?: string;+}++export interface StreamableHttpTransport {+ kind: 'streamable-http';+ url: string;+ headers?: Record<string, string>;+}++export interface ToolSchema {+ /** Tool name as reported by the MCP server (unprefixed). */+ name: string;+ description: string;+ input_schema: Record<string, unknown>;+}++export type ConnectorStatus =+ | { kind: 'connected'; since: number }+ | { kind: 'connecting' }+ | { kind: 'disconnected' }+ | { kind: 'error'; message: string; at: number };++export interface ConnectorInstance {+ /** Stable id chosen by the user at install time (e.g. "github-personal"). Becomes the prefix on+ * every tool name emitted into the AgentRunner tool list: `<id>__<tool_name>`. */+ id: string;+ display_name: string;+ transport: Transport;+ /** Tool subset to expose. `null` = all reported tools; `string[]` = whitelist of tool names. */+ enabled_subtools: string[] | null;+ /** Last-known tool schemas; used to assemble the LLM tools[] array without waiting for live+ * reconnect. Refreshed on every successful `list_tools` call. */+ tools_cache: ToolSchema[];+ tools_cached_at: number;+ status: ConnectorStatus;+ /** OAuth grant when this instance was created via OAuth; absent for API-key installs.+ * The manager rewrites the transport env at spawn time using `oauth_grant.access_token`;+ * refresh logic in `oauth.ts::refreshIfStale` runs before connect / after a 401. */+ oauth_grant?: OAuthGrant;+ /** DCR-issued client identity for MCP-spec auth (`auth_mode === 'mcp_dcr'`). Empty for+ * server-bridge instances. Refresh uses these directly against the provider's token endpoint+ * — Server is not involved post-install. */+ dcr_client?: DcrClientCredentials;+ created_at: string;+ updated_at: string;+}++export interface ConnectorsFile {+ version: 1;+ connections: Record<string, ConnectorInstance>;+}++export interface NewInstanceInput {+ id: string;+ display_name: string;+ transport: Transport;+ enabled_subtools?: string[] | null;+}++// ── Catalog ─────────────────────────────────────────────────────────────+// The UI doesn't accept arbitrary MCP server URLs / commands. Every connector the user can+// install is one of these curated entries. **Every entry uses OAuth 2.0** — no API-key fallback+// in the user-facing surface. (If we ever need a non-OAuth provider for an internal/enterprise+// case, that's a separate Phase 2 admin path, not in the curated catalog.)++export type TransportTemplate =+ | {+ kind: 'stdio';+ command: string;+ args: string[];+ /** The env var name to receive the bearer access_token at spawn time.+ * Mutually exclusive with `env_synthesizer` — pick one. */+ oauth_env_key?: string;+ /** Optional callback name resolved in `apply-template.ts` for MCP servers whose env shape+ * isn't a flat one-key map (Notion's `OPENAPI_MCP_HEADERS` packs a token into a JSON+ * blob). The synthesizer receives the resolved `access_token`. */+ env_synthesizer?: string;+ }+ | {+ kind: 'streamable-http';+ url: string;+ /** HTTP header name for the bearer (defaults to `Authorization: Bearer <token>`). */+ oauth_header_key?: string;+ };++// ── OAuth ───────────────────────────────────────────────────────────────+// Two auth_modes for catalog entries:+//+// - 'server_bridge' — Orkas company pre-registered an OAuth App at the provider. Server holds+// client_id/secret, runs the full OAuth handshake server-side, returns a token via deep-link.+// Used when the provider doesn't ship a public MCP authorization server (e.g. GitHub Copilot+// MCP today). Carries `oauth.provider_id` pointing at the Server's+// `biz/connectors/oauth/<provider>.py` module.+//+// - 'mcp_dcr' — Provider hosts an MCP-spec OAuth authorization server. Client (PC)+// self-registers via Dynamic Client Registration (RFC 7591) at runtime, runs the OAuth+// handshake from PC, uses the `/api/connectors/oauth/dcr-callback` Server endpoint **only**+// as an HTTPS callback intermediate (Server stashes code+state in a 5-min KV, deep-links+// PC). Server has no provider-specific knowledge. Used for Notion, Atlassian, Cloudflare+// suite, … — the modern path. PC stores DCR-issued client_id/secret on the instance.++export interface OAuthConfig {+ /** Server-bridge only: matches the Server's `biz/connectors/oauth/<provider>.py` module name+ * and the `/connectors/oauth/<provider>/start` URL path segment. */+ provider_id: string;+}++/** Dynamic Client Registration result (RFC 7591) for MCP-spec OAuth providers. Stored on the+ * ConnectorInstance so refreshes can re-use the same client identity and revoke at uninstall.+ * All endpoints captured at first connect — re-discovery on every refresh would add latency+ * and assumes provider doesn't rotate URLs (which they shouldn't). */+export interface DcrClientCredentials {+ client_id: string;+ /** Most providers issue one; some omit (public clients). */+ client_secret?: string;+ /** Captured from provider discovery — kept for refresh + revoke later. */+ authorization_endpoint: string;+ token_endpoint: string;+ /** Optional; used for revoke / re-registration (rarely needed). */+ registration_endpoint?: string;+ /** RFC 8707 canonical resource URI (from PRM `resource` field). MUST be sent on every+ * authorize / token / refresh request so the issued access_token is audience-bound to this+ * MCP server; without it the MCP server rejects the token at the first protected request+ * with `invalid_token`. */+ resource?: string;+}++export interface OAuthGrant {+ /** Current bearer token. */+ access_token: string;+ /** Long-lived rotation token; null when provider doesn't issue one. */+ refresh_token: string | null;+ /** Unix ms when `access_token` expires; null when provider doesn't say. */+ expires_at: number | null;+ /** Granted scope list (whatever the provider actually returned). */+ scopes: string[];+ /** Provider-returned token_type — usually 'Bearer'. */+ token_type: string;+ /** Optional human-readable label (e.g. the email associated with the grant). Filled by+ * per-provider modules' `fetch_account_label()` after exchange. */+ account_label?: string;+}++export type CatalogCategory =+ | 'developer'+ | 'productivity'+ | 'communication'+ | 'search'+ | 'data';++export type AuthMode = 'server_bridge' | 'mcp_dcr';++export interface CatalogEntry {+ /** Stable id; doubles as the installed instance id (one install per catalog entry in Phase 0).+ * Lowercase, [a-z0-9_-]+; used as the `<inst>__<tool>` prefix. */+ id: string;+ display_name: string;+ /** Inline SVG markup for the brand logo. Required on every shipped catalog entry — the+ * renderer draws this on a white rounded square. Keep the inner SVG `width` / `height`+ * either absent or `100%` so CSS-set 40×40 card box governs the rendered size.+ *+ * Optional only so `_entryFromInstance` (orphan-instance fallback when the catalog entry+ * was removed but the install still exists) can omit it; the orphan path renders the+ * display_name initials on a neutral gray placeholder. */+ icon_svg?: string;+ category: CatalogCategory;+ description_zh: string;+ description_en: string;+ /** Which OAuth pathway this provider needs — see the `// ── OAuth ──` section above. */+ auth_mode: AuthMode;+ /** Required when `auth_mode === 'server_bridge'`; absent for `'mcp_dcr'` (no pre-registration). */+ oauth?: OAuthConfig;+ /** MCP server config + how the access_token maps into env / headers. Null when this entry is+ * catalogued but not yet installable (we don't have an MCP server target for it yet).+ * Renderer surfaces a disabled "敬请期待" state. */+ transport_template: TransportTemplate | null;+ /** Set when `transport_template` is null to explain why; renderer surfaces in the badge. */+ unavailable_reason?: 'oauth_pending';+}diff --git a/src/main/features/group_chat/state.ts b/src/main/features/group_chat/state.tsindex 7ff20a9f..df057120 100644--- a/src/main/features/group_chat/state.ts+++ b/src/main/features/group_chat/state.ts@@ -76,6 +76,10 @@ export interface StateFile {* per-conversation, NOT per-agent: one project for the whole* conversation across however many coding agents it has. */coding_project_dir?: string;+ /** True once this conversation has been touched by the iOS remote-control+ * client (a relayed command landed on this PC, or the user opted in).+ * appended messages + plan/state up to the Server so the phone can watch+ * progress. Only `true` is recorded; absent = not relayed. *//** True when the user picked `coding_project_dir` explicitly via the* `<agent-input-form>` directory picker (form-submit hook in* `group_chat/index.ts`). False / missing means the dir was@@ -370,6 +374,15 @@ export async function setCodingProjectDir(});}+/** Mark / unmark this conversation as relay-enabled (mirrored to the iOS client — see+ return _stateLock(uid, cid).runExclusive(async () => {+ const s = await readState(uid, cid);+ s.last_active_at = nowIso();+ await writeStateRaw(uid, cid, s);+ return s;+ });+}+/** Drop the whole group dir (called from chats.deleteConversation). */export async function purgeGroupDir(uid: string, cid: string): Promise<void> {const dir = groupChatDir(uid, cid);diff --git a/src/main/features/sessions_sweep.ts b/src/main/features/sessions_sweep.tsnew file mode 100644index 00000000..7b5b6759--- /dev/null+++ b/src/main/features/sessions_sweep.ts@@ -0,0 +1,213 @@+/**+ * Sessions GC — startup-time sweep of `<uid>/{cloud,local}/sessions/`.+ *+ * Design lives upstream:+ * - "Resumable" kinds (gconv / gmember / skill / agent) belong in+ * cloud/sessions/ and are life-cycled with their owning entity (cid /+ * sid / aid). Their normal cleanup path is the owning entity's delete+ * (chats.deleteConversation / skills.deleteCustomSkill /+ * agents.deleteCustomAgent). The sweep is a defense in depth for+ * cid-bound orphans only — skill / agent orphans are explicitly NOT+ * touched per user instruction (their per-entity delete already hooks+ * evictSession + unlink).+ * - "Ephemeral" kinds (extract-img / reflect / memory-extract / anon)+ * are routed to `local/sessions/` by `session-store.resolveSessionPath`.+ * They have no resumer, so we GC by mtime.+ *+ * Sweep targets (only these — everything else is left alone):+ * 1. cloud/sessions/ — ephemeral kinds that pre-date the routing change+ * (one-shot historical clean-up after the path+ * migration; the post-change code never writes+ * ephemeral kinds here).+ * 2. cloud/sessions/ — gconv / gmember orphans where the cid is no+ * longer in conversations._index.json (this was+ * the historical bug — dropConv removed members.json+ * before deleteConversation got to read it, leaking+ * every per-agent worker session).+ * 3. cloud/sessions/ — legacy prefix kinds (sub / organizer / conv);+ * new code doesn't write these and the legacy id+ * migrator in features/users.ts only renames live+ * ids, not the orphan files.+ * 4. local/sessions/ — mtime older than EPHEMERAL_AGE_MS.+ */++import * as fs from 'node:fs';+import * as fsp from 'node:fs/promises';+import * as path from 'node:path';++import { userSessionsDir, userLocalSessionsDir } from '../paths';+import { createLogger } from '../logger';+import { listConversations } from './chats';+import { isEphemeralSessionId } from '../model/core-agent/session-store';++const log = createLogger('sessions-sweep');++const EPHEMERAL_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days (matches logger / marketplace_cache)+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+ local_aged_out: number; // local/sessions/ files older than EPHEMERAL_AGE_MS+ 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.+ for (const k of ['extract-img', 'memory-extract']) {+ if (tail.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);+ 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.)+ const lastDash = rest.lastIndexOf('-');+ if (lastDash < 0) return { kind, cid: rest };+ return { kind, cid: rest.slice(0, lastDash) };+ }+ return { kind };+}++async function sweepCloud(userId: string, result: SweepResult): Promise<void> {+ const dir = userSessionsDir(userId);+ let names: string[];+ try { names = await fsp.readdir(dir); }+ catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(`readdir cloud sessions: ${(err as Error).message}`);+ }+ return;+ }+ // Materialize the active cid set once — listConversations does a JSON+ // read; doing it per-file would be n× wasteful.+ const activeCids = new Set<string>();+ try {+ const convs = await listConversations(userId);+ for (const c of convs) activeCids.add(c.conversation_id);+ } catch (err) {+ log.warn(`listConversations failed; orphan-cid sweep degraded: ${(err as Error).message}`);+ }+ for (const name of names) {+ if (!name.endsWith('.jsonl')) continue;+ 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);+ if (!info) continue;+ let reason: keyof Pick<SweepResult, 'orphan_cid' | 'ephemeral_on_cloud' | 'legacy'> | null = null;+ if (isEphemeralSessionId(userId, sid)) {+ reason = 'ephemeral_on_cloud';+ } else if (LEGACY_KINDS.has(info.kind)) {+ reason = 'legacy';+ } else if ((info.kind === 'gconv' || info.kind === 'gmember') && info.cid && !activeCids.has(info.cid)) {+ reason = 'orphan_cid';+ }+ if (!reason) continue;+ try {+ await fsp.unlink(path.join(dir, name));+ result[reason]++;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(`unlink ${name}: ${(err as Error).message}`);+ result.errors++;+ }+ }+ }+}++async function sweepLocalByAge(userId: string, result: SweepResult, now: number): Promise<void> {+ const dir = userLocalSessionsDir(userId);+ let names: string[];+ try { names = await fsp.readdir(dir); }+ catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(`readdir local sessions: ${(err as Error).message}`);+ }+ return;+ }+ for (const name of names) {+ if (!name.endsWith('.jsonl')) continue;+ const full = path.join(dir, name);+ let st: fs.Stats;+ try { st = await fsp.stat(full); }+ catch { continue; }+ if (now - st.mtimeMs <= EPHEMERAL_AGE_MS) continue;+ try {+ await fsp.unlink(full);+ result.local_aged_out++;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(`unlink ${name}: ${(err as Error).message}`);+ result.errors++;+ }+ }+ }+}++/** Run the sweep for a specific uid. Logs a summary line at the end; safe+ * to call from startup without awaiting (errors don't propagate). */+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,+ 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+ + 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,+ local_aged_out: result.local_aged_out,+ errors: result.errors,+ ms: Date.now() - t0,+ });+ }+ return result;+}diff --git a/src/main/features/users.ts b/src/main/features/users.tsindex fee19240..583ccd3b 100644--- a/src/main/features/users.ts+++ b/src/main/features/users.ts@@ -120,6 +120,18 @@ export function activateUser(uid: string): void {catch (err) { log.warn(`sweepToolResults uid=${uid}: ${(err as Error).message}`); }// Strip legacy session_id brand prefixes once.+ // Sessions GC: clean cid-orphan / legacy-kind / leaked-ephemeral in+ // cloud/sessions/, and mtime>7d in local/sessions/. Fire-and-forget — the+ // file scan is bounded by the size of sessions/ and shouldn't gate startup.+ // See features/sessions_sweep.ts for what it does and doesn't touch.+ (async () => {+ try {+ const mod = await import('./sessions_sweep');+ await mod.sweepSessions(uid);+ } catch (err) { log.warn(`sweepSessions uid=${uid}: ${(err as Error).message}`); }+ })();++ // Strip legacy session_id prefixes (aiteam- / orkas-) once.// Idempotent: after the stamp lands, subsequent startups are no-ops.// See util/migrate-session-ids.ts for details.try { migrateLegacySessionIds(uid); }diff --git a/src/main/index.ts b/src/main/index.tsindex 5b76dbea..be250ef4 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -134,6 +134,8 @@ import * as scheduledTasks from './features/scheduled_tasks';import * as chatAttachments from './features/chat_attachments';import * as chatArtifacts from './features/chat_artifacts';// `features/sync/*` and `ipc/sync.ts` are stripped in OrkasOpen (depends on account).+import * as connectorsFeature from './features/connectors';+// (sync + relay both depend on account; connectors depends on the Server OAuth bridge).function createWindow(): BrowserWindow {@@ -713,6 +715,12 @@ if (!gotLock) {registerIpc();createWindow();+ // Reconnect persisted MCP connector instances + register the before-quit shutdown hook.+ // Independent of account: connectors are machine-local and work for any active uid.+ connectorsFeature.bootstrap(users.getActiveUserId()).catch(() => {+ /* errors logged inside the feature; never block app startup */+ });+// Background: pick up any out-of-band changes to source files (sync// drop-in, manual edits) into the search idx. Query path does not run// reconcile — this is the only place it fires during normal op.diff --git a/src/main/ipc/connectors.ts b/src/main/ipc/connectors.tsnew file mode 100644index 00000000..e6db01e5--- /dev/null+++ b/src/main/ipc/connectors.ts@@ -0,0 +1,62 @@+/**+ * IPC handlers for the connectors feature. Renderer reaches these via+ * `window.orkas.invoke('connectors.*', payload)`.+ *+ * connectors.catalog → { catalog }+ * connectors.list → { instances }+ * connectors.start_oauth → { instance } (Server-bridge OAuth; blocks until deep-link returns)+ * connectors.remove → { removed }+ * connectors.refresh → { tools }+ * connectors.set_subtools → { instance }+ *+ * **OAuth is the only install path** — no free-form transport, no API-key entry, no BYO client+ * credentials. Server holds every provider's `client_id` / `client_secret`. PC just kicks off+ * the flow and waits for the deep-link callback.+ */+import * as connectors from '../features/connectors';++export const invokeHandlers = {+ 'connectors.catalog': async () => ({ catalog: connectors.CONNECTOR_CATALOG }),++ 'connectors.list': async (_payload: unknown, ctx: { userId: string }) => ({+ instances: connectors.listInstances(ctx.userId),+ }),++ 'connectors.start_oauth': async (payload: { catalog_id?: unknown }, ctx: { userId: string }) => {+ if (typeof payload?.catalog_id !== 'string') throw new Error('invalid catalog_id');+ const instance = await connectors.connectViaOAuth(ctx.userId, payload.catalog_id);+ return { instance };+ },++ 'connectors.cancel_oauth': async () => {+ const cancelled = connectors.cancelInFlightOAuth();+ return { cancelled };+ },++ 'connectors.remove': async (payload: { id?: unknown }, ctx: { userId: string }) => {+ if (typeof payload?.id !== 'string') throw new Error('invalid id');+ const removed = await connectors.removeInstance(ctx.userId, payload.id);+ return { removed };+ },++ 'connectors.refresh': async (payload: { id?: unknown }, ctx: { userId: string }) => {+ if (typeof payload?.id !== 'string') throw new Error('invalid id');+ const tools = await connectors.refreshTools(ctx.userId, payload.id);+ return { tools };+ },++ 'connectors.set_subtools': async (+ payload: { id?: unknown; subtools?: unknown },+ ctx: { userId: string },+ ) => {+ if (typeof payload?.id !== 'string') throw new Error('invalid id');+ let subset: string[] | null;+ if (payload.subtools === null) subset = null;+ else if (Array.isArray(payload.subtools)) {+ subset = payload.subtools.filter((s): s is string => typeof s === 'string');+ } else throw new Error('subtools must be null or string[]');+ const instance = await connectors.setEnabledSubtools(ctx.userId, payload.id, subset);+ if (!instance) throw new Error('instance not found');+ return { instance };+ },+};diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex ac56ce70..0e742c82 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -46,6 +46,7 @@ import * as avatars from '../features/avatars';import { getRendererTables, isLang, t } from '../i18n';import * as userWorkspace from '../features/user_workspace';import { invokeHandlers as localAgentsHandlers } from './local_agents';+import { invokeHandlers as connectorsHandlers } from './connectors';import { safeId } from '../storage';import { createLogger, logFromRenderer } from '../logger';import * as path from 'node:path';@@ -1071,6 +1072,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {// User-account login (Google / Apple OAuth). Stripped from the OrkasOpen build.// Multi-device sync. Stripped from the OrkasOpen build (depends on account).++ // Connectors (MCP-based). User-installed MCP servers expose tools to commander + selected+ // agents. No Server dependency → kept in OrkasOpen.+ ...connectorsHandlers,};// ── Stream handlers ──────────────────────────────────────────────────────diff --git a/src/main/model/core-agent/connector-meta-tools.ts b/src/main/model/core-agent/connector-meta-tools.tsnew file mode 100644index 00000000..2aab6be9--- /dev/null+++ b/src/main/model/core-agent/connector-meta-tools.ts@@ -0,0 +1,275 @@+/**+ * Connector umbrella meta-tools + system-prompt block.+ *+ * Replaces the old "flat-inject every connected MCP tool into tools[]" pattern. Motivation is+ * scale: at 30–50 tools the model's selection accuracy drops sharply (Anthropic 30–50 / Cline+ * ~20 / Cursor ~40 / Copilot 128 hard-cap with degradation well below); flat injection also+ * means every connect/disconnect rewrites `tools` and invalidates the entire Anthropic prompt-+ * cache prefix (`tools → system → messages`).+ *+ * Architecture:+ * 1. The list of connected (and visible) connectors is rendered as a `## Connectors` markdown+ * block injected into the system prompt — `getConnectorPromptBlock`. The block is stable+ * per session and lives in the cached prefix; the model sees the names + descriptions+ * without a discovery round-trip.+ * 2. Two meta-tools enable lazy disclosure of each connector's per-action schema:+ * list_connector_tools(connector_id) → MCP tool schemas for one connector+ * call_connector_tool(connector_id, …) → route to manager.callTool+ * 3. When NO connector is visible to this actor, both the prompt block and the meta-tools are+ * omitted entirely — `tools[]` shrinks by two slots and the system prompt stays smaller.+ *+ * Visibility: commander sees every connected instance; agent worker is gated by+ * `agent.enabled_connectors` (intentionally stricter than `agent.skill_list` — see+ * PC/CLAUDE.md §6.5). The `enabled_subtools` instance-level whitelist further filters which+ * actions each connector advertises. The two meta-tools share `resolveVisibleConnectors` so the+ * matrix is single-sourced.+ *+ * Session-kind gate: callers (runner.ts) only invoke this module for `gconv` + `gmember`+ * sessions. Edit chats / KB-image extraction / CLI dispatch / reflect / memory-extract / anon+ * don't run user tasks against external services and stay free of connector exposure.+ */+import type { AgentTool, ToolResult } from '#core-agent';++import * as manager from '../../features/connectors/manager';+import {+ resolveVisibleConnectors,+ stringifyMcpResult,+} from '../../features/connectors/tools-adapter';+import { findCatalogEntry } from '../../features/connectors/catalog';+import { getCurrentLang } from '../../i18n';+import { createLogger } from '../../logger';+import type { ConnectorInstance, ToolSchema } from '../../features/connectors/types';++const log = createLogger('connector-meta-tools');++export interface ConnectorMetaToolsOpts {+ /** Active uid. Required — without it the meta-tools have no scope. */+ userId: string;+ /** Agent id when running as an agent worker. Empty / undefined = commander scope (no+ * `enabled_connectors` filter). */+ agentId?: string;+}++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).+ 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)}`;+}++/** Render the `## Connectors` system-prompt block — pure enumeration (one line per connector).+ * Returns `''` when nothing is visible; the caller skips concatenation in that case. The block+ * is stable per session (only changes on connect / disconnect events) so it sits in the cached+ * prompt prefix. The protocol for invoking connectors via the meta-tools is taught in the+ * per-role chat prompts (`chat_commander.md` / `chat_agent_in_group.md`); the agent-edit+ * prompt teaches the "reference connectors by id in the workflow" usage. Keeping the+ * protocol out of the block lets each role frame its own use without duplication. */+export async function getConnectorPromptBlock(uid: string, agentId: string | undefined): Promise<string> {+ if (!uid) return '';+ const visible = await resolveVisibleConnectors(uid, agentId);+ if (!visible.length) return '';+ const lines: string[] = ['## Connectors', ''];+ for (const { instance } of visible) lines.push(_renderConnectorLine(instance));+ return lines.join('\n');+}++function createListConnectorToolsTool(opts: ConnectorMetaToolsOpts): AgentTool {+ return {+ name: 'list_connector_tools',+ description:+ 'Discover the actions available on a specific connector (the system prompt\'s `## Connectors` ' ++ 'block lists which connector ids exist for this conversation). Returns each action\'s name, ' ++ 'description, and JSON input schema — use the schema verbatim to construct the `args` for ' ++ '`call_connector_tool`. Errors when the connector id is not visible to this actor or is ' ++ 'currently disconnected.',+ inputSchema: {+ type: 'object',+ properties: {+ connector_id: {+ type: 'string',+ description: 'The connector id from the `## Connectors` system-prompt block.',+ },+ },+ required: ['connector_id'],+ },+ async execute(input) {+ const cid = typeof (input as { connector_id?: unknown }).connector_id === 'string'+ ? ((input as { connector_id: string }).connector_id).trim()+ : '';+ if (!cid) return errResult('E_BAD_INPUT', '`connector_id` is required (a non-empty string)');++ const visible = await resolveVisibleConnectors(opts.userId, opts.agentId);+ const match = visible.find((v) => v.instance.id === cid);+ if (!match) {+ 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".',+ );+ }+ if (!match.tools.length) {+ return {+ content: `Connector "${cid}" reports no actions. Ask the user to refresh it from the Connectors panel.`,+ };+ }++ const lines: string[] = [+ `Actions on connector "${cid}". Invoke any of them via ` ++ `\`call_connector_tool({connector_id: "${cid}", tool_name: "<name>", args: {…}})\` — ` ++ '`args` MUST match the listed input_schema verbatim.',+ '',+ ];+ for (const t of match.tools) {+ lines.push(`### ${t.name}`);+ lines.push(t.description || '(no description)');+ lines.push('');+ lines.push('Input schema:');+ lines.push('```json');+ try {+ lines.push(JSON.stringify(t.input_schema ?? {}, null, 2));+ } catch {+ lines.push('{}');+ }+ lines.push('```');+ lines.push('');+ }+ return { content: lines.join('\n').trimEnd() };+ },+ };+}++function createCallConnectorToolTool(opts: ConnectorMetaToolsOpts): AgentTool {+ return {+ name: 'call_connector_tool',+ description:+ 'Invoke a specific action on a connected third-party service. Always call ' ++ '`list_connector_tools(connector_id)` first (in this conversation) to learn the action ' ++ 'name and its input schema; then construct `args` to match that schema. The result is ' ++ 'the connector\'s response (text / JSON), exactly as the underlying service returned it.',+ inputSchema: {+ type: 'object',+ properties: {+ connector_id: {+ type: 'string',+ description: 'The connector id from the `## Connectors` system-prompt block.',+ },+ tool_name: {+ type: 'string',+ description: 'The action name from `list_connector_tools`.',+ },+ args: {+ type: 'object',+ description: 'Arguments matching the action\'s `input_schema`. Must be a JSON object.',+ },+ },+ required: ['connector_id', 'tool_name', 'args'],+ },+ async execute(input) {+ const i = input as { connector_id?: unknown; tool_name?: unknown; args?: unknown };+ const cid = typeof i.connector_id === 'string' ? i.connector_id.trim() : '';+ const toolName = typeof i.tool_name === 'string' ? i.tool_name.trim() : '';+ if (!cid || !toolName) {+ return errResult('E_BAD_INPUT', '`connector_id` and `tool_name` are both required non-empty strings');+ }+ // Accept both `args: {}` and `args: "{}"`. Models routinely stringify nested JSON when the+ // outer call already serializes through JSON — re-parsing here keeps the meta-tool ergonomic+ // and avoids retry loops where the model just sends the same shape again (we saw GitHub+ // get_me hit this twice in a row before the parse fallback). Reject only when the input is+ // neither a JSON object nor a string that parses to one.+ let args: Record<string, unknown> | null = null;+ if (i.args && typeof i.args === 'object' && !Array.isArray(i.args)) {+ args = i.args as Record<string, unknown>;+ } else if (typeof i.args === 'string') {+ const s = i.args.trim();+ if (s === '' || s === '{}') {+ args = {};+ } else {+ try {+ const parsed: unknown = JSON.parse(s);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ args = parsed as Record<string, unknown>;+ }+ } catch { /* fall through to error below */ }+ }+ }+ if (args === null) {+ return errResult('E_BAD_INPUT', '`args` is required and must be a JSON object (use {} for no-arg actions)');+ }++ const visible = await resolveVisibleConnectors(opts.userId, opts.agentId);+ const match = visible.find((v) => v.instance.id === cid);+ if (!match) {+ return errResult(+ 'E_CONNECTOR_NOT_VISIBLE',+ `connector "${cid}" is not enabled for this conversation. See the \`## Connectors\` system-prompt block for valid ids.`,+ );+ }+ const toolMatch = match.tools.find((t) => t.name === toolName);+ if (!toolMatch) {+ return errResult(+ 'E_TOOL_NOT_AVAILABLE',+ `action "${toolName}" is not available on connector "${cid}". ` ++ `Call list_connector_tools({connector_id: "${cid}"}) to see the actual action names.`,+ );+ }++ try {+ const raw = await manager.callTool(opts.userId, cid, toolName, args);+ return { content: stringifyMcpResult(raw) };+ } catch (err) {+ const msg = (err as Error).message;+ log.warn(`call_connector_tool failed connector=${cid} tool=${toolName}: ${msg}`);+ return {+ content: `Error calling ${cid}/${toolName}: ${msg}`,+ isError: true,+ };+ }+ },+ };+}++/** 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[]> {+ if (!opts.userId) return [];+ const visible = await resolveVisibleConnectors(opts.userId, opts.agentId);+ if (!visible.length) return [];+ return [+ createListConnectorToolsTool(opts),+ createCallConnectorToolTool(opts),+ ];+}diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.tsindex 76de0e69..f25b283f 100644--- a/src/main/model/core-agent/runner.ts+++ b/src/main/model/core-agent/runner.ts@@ -47,6 +47,7 @@ import { EXTERNAL_API_PROVIDERS } from '../provider_catalog';import { readDisabledSets } from '../../features/component_enabled';import { nativeSearchToolForApi, nativeSearchToolName } from './native-search-tools';import { hasAnySearchProfile } from '../../features/search_auth';+import { createConnectorMetaTools, getConnectorPromptBlock } from './connector-meta-tools';import { createLogger } from '../../logger';import type { MemoryToolHandler } from '../../../core-agent/src/tools/memory-tool';import type { MetacognitionToolHandler } from '../../../core-agent/src/tools/metacognition-tool';@@ -287,6 +288,39 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{// off the ESM core-agent dynamic import.const searchOverrideTools: AgentTool[] = [await createWebSearchOverrideTool()];+ // Connector meta-tools + system-prompt block (MCP-based, umbrella pattern). When ≥1+ // connector is visible to this actor we inject the two meta-tools (`list_connector_tools` /+ // `call_connector_tool`) plus a `## Connectors` block enumerating the connectors directly in+ // the system prompt — the model sees the catalog without a discovery round-trip, and the+ // block sits in the cached prefix. When 0 visible: zero tools, no block. Per-connector MCP+ // actions are NEVER injected into `tools[]` — the model discovers and invokes them through+ // the meta-tools (umbrella pattern); flat-injecting would balloon `tools[]` past the 20–50+ // 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)+ // - everything else (skill-edit / KB-image / CLI dispatch / reflect / memory-extract /+ // anon) → none (no accidental external side+ // effects from non-task sessions)+ // 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 connectorBlock = exposure !== 'none' && uid+ ? await getConnectorPromptBlock(uid, blockAgentId)+ : '';+ const connectorMetaTools = exposure === 'tools+block' && uid+ ? await createConnectorMetaTools({ userId: uid, ...(agentId ? { agentId } : {}) })+ : [];+// Merge injected tools with extra tools from callerconst allTools = [...injectedTools,@@ -296,6 +330,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{...imageGenTools,...searchOverrideTools,...(params.extraTools || []),+ ...connectorMetaTools,];// Cap each tool's result size + persist oversized outputs. Single wrap point@@ -358,6 +393,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{const parts: string[] = [];if (params.systemPrompt) parts.push(params.systemPrompt.trim());if (skillsBlock) parts.push(skillsBlock.trim());+ if (connectorBlock) parts.push(connectorBlock.trim());const resolvedSystemPrompt = parts.join('\n\n');// Evolution (the self-evolving skill store) is per-agent: when an@@ -447,10 +483,43 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{};}-/** Extract userId from session_id format: `<uid>-<kind>-...` */-function extractUidFromSessionId(sessionId: string): string | null {- const m = sessionId.match(/^([^-]+)-/);- return m ? m[1] : null;+/** 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;+}++/** 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+ * 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.+ *+ * 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';+ return 'none';}/**diff --git a/src/main/model/core-agent/session-store.ts b/src/main/model/core-agent/session-store.tsindex a8c995ad..021d0006 100644--- a/src/main/model/core-agent/session-store.ts+++ b/src/main/model/core-agent/session-store.ts@@ -27,37 +27,69 @@import * as path from 'node:path';import * as fs from 'node:fs';-import { userSessionFile } from '../../paths';+import { userSessionFile, userLocalSessionFile } from '../../paths';import { getActiveUserId } from '../../features/users';import { createLogger } from '../../logger';const log = createLogger('model');/**- * Build the filesystem path that backs a given session id.+ * "Ephemeral" kinds — one-shot background LLM calls that nobody resumes:+ * extract-img — KB image understanding (single image → description)+ * reflect — agent metacognition / reflection+ * memory-extract — periodic fact extraction from compaction summaries+ * anon — fallback when a caller of `streamChatWithModel` didn't+ * pass a sessionId (auto-generated by client.ts)+ * These land under `<uid>/local/sessions/` so they:+ * - never cross devices (sync cost = 0 for throwaway transcripts);+ * - GC out of band via `features/sessions_sweep.ts` (mtime-based 7d).+ * Every other kind (gconv / gmember / skill / agent) is "resumable" and+ * stays in `cloud/sessions/`, life-cycled with its owning entity (cid /+ * sid / aid).+ */+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);+ for (const kind of EPHEMERAL_KINDS) {+ if (tail === kind || tail.startsWith(`${kind}-`)) return true;+ }+ return false;+}++/**+ * 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 `<activeUid>-`, i.e. the active- * user's id sits in the first segment. This blocks the legacy format- * `<kind>-<uid>-<tail>` (used by extract/organizer before the rewrite)- * from silently routing user-private jsonl to `data/<kind>/sessions/`.+ * 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.** Constructors (chats / group_chat / agents-edit / skills-edit / kb image* extract / reflection) must build ids via the feature-layer helpers; never* by hand.*/-export function sessionFileFor(sessionId: string): string {- const uid = getActiveUserId();- const prefix = `${uid}-`;+export function resolveSessionPath(userId: string, sessionId: string): string {+ const prefix = `${userId}-`;if (!sessionId.startsWith(prefix)) {throw new Error(- `invalid session id "${sessionId}" — must start with "${prefix}" (active user is ${uid})`,+ `invalid session id "${sessionId}" — must start with "${prefix}" (user is ${userId})`,);}- // tail must be non-empty (i.e. there's something after the uid segment).if (sessionId.length <= prefix.length) {throw new Error(`invalid session id "${sessionId}" — missing kind/tail after uid`);}- return userSessionFile(uid, sessionId);+ return isEphemeralSessionId(userId, sessionId)+ ? userLocalSessionFile(userId, sessionId)+ : userSessionFile(userId, sessionId);+}++export function sessionFileFor(sessionId: string): string {+ return resolveSessionPath(getActiveUserId(), sessionId);}/**@@ -112,6 +144,19 @@ export function deleteSessionFile(sessionId: string): void {}}+/** Same as deleteSessionFile but takes an explicit userId (caller has the+ * uid in scope and doesn't want to depend on the global active uid — e.g.+ * chats.deleteConversation passes ctx.userId). */+export function deleteSessionFileForUser(userId: string, sessionId: string): void {+ const file = resolveSessionPath(userId, sessionId);+ try { fs.unlinkSync(file); }+ catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ log.warn(`delete failed ${file}: ${(err as Error).message}`);+ }+ }+}+/** Flush all cached sessions — called by `features/users.activateUser()` on uid switch. */export function _evictAll(): void {cache.clear();diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.tsindex 19619096..013017ff 100644--- a/src/main/model/core-agent/tool-catalog.ts+++ b/src/main/model/core-agent/tool-catalog.ts@@ -15,6 +15,15 @@* Anti-drift: `tool-catalog.test.ts` asserts that the set of tool names* runner.ts actually injects is a subset of `TOOL_CATALOG`. Forgetting* a catalog entry → test red.+ *+ * Connectors (Notion / Slack / GitHub / Gmail / …) are surfaced through two umbrella meta-+ * tools (`list_connector_tools` / `call_connector_tool`) PLUS a `## Connectors` system-prompt+ * block enumerating connector ids + descriptions. Both are injected only when ≥1 connector is+ * visible to the current actor; otherwise zero connector slots in `tools[]`. The two meta-+ * tools are static and ARE in this catalog; the per-connector MCP actions discovered at+ * runtime are NOT enumerated here (they vary per-user / per-install). See+ * `connector-meta-tools.ts` for the rationale (tool-selection accuracy cliff at 20–50 tools ++ * prompt-cache stability).*/import { createLogger } from '../../logger';@@ -22,14 +31,15 @@ import { createLogger } from '../../logger';const log = createLogger('tool-catalog');export type ToolGroup =- | 'fs' // files / workspace- | 'shell' // command line- | 'pdf' // PDF rendering- | 'kb' // knowledge base- | 'image' // image generation- | 'web' // web access- | 'meta' // cross-session state- | 'group'; // group-chat dispatch (commander only)+ | 'fs' // files / workspace+ | 'shell' // command line+ | 'pdf' // PDF rendering+ | 'kb' // knowledge base+ | 'image' // image generation+ | 'web' // web access+ | 'connector' // third-party services via MCP umbrella tools+ | 'meta' // cross-session state+ | 'group'; // group-chat dispatch (commander only)export interface ToolCatalogEntry {/** Tool name. Must match `AgentTool.name` exactly. */@@ -79,6 +89,12 @@ export const TOOL_CATALOG: ToolCatalogEntry[] = [{ name: 'web_search', group: 'web', summary: 'Built-in fallback web search (vendor-native search is preferred automatically when available).' },{ name: 'web_fetch', group: 'web', summary: 'Fetch the body of a URL; pairs with web_search.' },+ // Connectors (umbrella meta-tools — actual MCP actions are discovered + invoked via these;+ // injected only when at least one connector is visible to the actor, alongside a+ // `## Connectors` system-prompt block listing the connector ids + descriptions)+ { name: 'list_connector_tools', group: 'connector', summary: 'Discover the actions a specific connector exposes (returns name + JSON input schema for each).' },+ { name: 'call_connector_tool', group: 'connector', summary: 'Invoke an action on a connector; call list_connector_tools first to learn the action name and schema.' },+// Cross-session state{ name: 'cross_session_memory', group: 'meta', summary: 'Read/write user / agent memory that persists across sessions.' },{ name: 'metacognition', group: 'meta', summary: 'Read/write metacognition (COMPETENCE / LEARNING_STRATEGIES); env-flag gated.' },@@ -95,8 +111,9 @@ const GROUP_ORDER: ReadonlyArray<{ group: ToolGroup; title: string }> = [{ group: 'pdf', title: 'PDF' },{ group: 'kb', title: 'Knowledge base' },{ group: 'image', title: 'Image' },- { group: 'web', title: 'Web' },- { group: 'meta', title: 'Cross-session state' },+ { group: 'web', title: 'Web' },+ { group: 'connector', title: 'Connectors (third-party services)' },+ { group: 'meta', title: 'Cross-session state' },{ group: 'group', title: 'Group-chat dispatch' },];diff --git a/src/main/paths.ts b/src/main/paths.tsindex df693066..12f6638b 100644--- a/src/main/paths.ts+++ b/src/main/paths.ts@@ -127,10 +127,19 @@ export const artifactDir = (uid: string, cid: string, artifactId: strinexport const userSavedAppsDir = (uid: string) => path.join(userCloudRoot(uid), 'saved_apps');export const savedAppDir = (uid: string, appId: string) => path.join(userSavedAppsDir(uid), appId);-// core-agent session jsonl (LLM-view) — all session kinds land here:-// conv (legacy) / gconv / gmember / skill / agent / extract-img.+// core-agent session jsonl (LLM-view). Two regions:+// cloud/sessions/ — "resumable" kinds: gconv / gmember / skill / agent.+// The user (or the system on the user's behalf) may continue these+// conversations later, so the LLM history must cross devices.+// local/sessions/ — "ephemeral" kinds: extract-img / reflect /+// memory-extract / anon. One-shot background calls; nobody resumes them,+// and they're large + worthless to sync. Sessions_sweep GCs by mtime.+// Routing lives in `model/core-agent/session-store.ts::resolveSessionPath`+// and is the single place that decides which side an id lands on.export const userSessionsDir = (uid: string) => path.join(userCloudRoot(uid), 'sessions');export const userSessionFile = (uid: string, sessionId: string) => path.join(userSessionsDir(uid), `${sessionId}.jsonl`);+export const userLocalSessionsDir = (uid: string) => path.join(userLocalRoot(uid), 'sessions');+export const userLocalSessionFile = (uid: string, sessionId: string) => path.join(userLocalSessionsDir(uid), `${sessionId}.jsonl`);// Curated knowledge base (the "organized" region of the historical// two-region contexts design).@@ -226,6 +235,13 @@ export const userLocalConfigDir = (uid: string) => path.join(userLocalRoot(uidexport const userAuthProfilesFile = (uid: string) => path.join(userLocalConfigDir(uid), 'auth-profiles.json');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 inverteddiff --git a/src/main/prompts/chat_agent_in_group.md b/src/main/prompts/chat_agent_in_group.mdindex 278745b5..42e8c3e7 100644--- a/src/main/prompts/chat_agent_in_group.md+++ b/src/main/prompts/chat_agent_in_group.md@@ -113,6 +113,8 @@ The "Runtime injection" section at the end lists your `inputs_schema`. If it is**Tools** are auto-registered via the tool-use protocol — call them by name (`read_file` / `bash` / `kb_search` / `web_search` / `markdown_to_pdf`, etc.). **Skills** are listed in the system prompt's `## Available skills (skills)` section; locate the detailed usage based on `Source` (`cat` the corresponding `SKILL.md`) — don't try both roots.+**Connectors**: when the system prompt has a `## Connectors` block, invoke listed services via `list_connector_tools({connector_id})` (to see an action's JSON schema) then `call_connector_tool({connector_id, tool_name, args})`. List before calling — don't guess. If the needed service isn't listed, tell the dispatcher; don't fake it with `web_search` / `bash`.+> Generic tool rules (PDF / search / file output / `chat-media://local`) are in the "Shared rules" section below.---diff --git a/src/main/prompts/chat_agent_setup.md b/src/main/prompts/chat_agent_setup.mdindex bf219c0c..0c3e65bc 100644--- a/src/main/prompts/chat_agent_setup.md+++ b/src/main/prompts/chat_agent_setup.md@@ -29,7 +29,8 @@ This is the per-agent inline edit chat — the agent you're refining is identifi3. **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.- - **Only when neither 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.+ - **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.+ - **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.5. If the user asks something unrelated to the agent, just answer normally; afterwards, ask if they want to keep refining.diff --git a/src/main/prompts/chat_commander.md b/src/main/prompts/chat_commander.mdindex bfb0f859..5cbaff08 100644--- a/src/main/prompts/chat_commander.md+++ b/src/main/prompts/chat_commander.md@@ -231,6 +231,10 @@ Read the matching SKILL.md **before** emitting any `<agent>` / `<skill>` contain`kb_search(query, k?, dir?, kind?)` + `kb_read(path, chunk?, window?)`: search first, read on demand. After a hit, use `window: 1~2` to bring back adjacent chunks — small embedding unit (precise recall) + larger context unit (enough to answer) — both matter.+### Connectors (third-party services)++When the system prompt has a `## Connectors` block, those services are reachable via `list_connector_tools({connector_id})` (to see an action's JSON input schema) then `call_connector_tool({connector_id, tool_name, args})`. List before calling — don't guess action names. If the user asks for a service the block doesn't list, tell them to add it via the Connectors panel; don't fake it with `web_search` / `bash`.+### Attachments and filesWhen a user message has an `<attachments>` prefix, each `<file name=... path=... kind=... [total_chars=...]/>` entry's `path` is the **authoritative absolute path**.diff --git a/src/main/util/crypto-vault.ts b/src/main/util/crypto-vault.tsnew file mode 100644index 00000000..d52314b9--- /dev/null+++ b/src/main/util/crypto-vault.ts@@ -0,0 +1,87 @@+/**+ * Local-file encryption for credential-bearing JSON files (`connectors.json`, `auth-profiles.json`).+ *+ * Design intent — **obfuscation, not security**: the key is derived deterministically from a+ * compiled-in app salt + the active user's uid, so anyone who runs Orkas can decrypt their own+ * files (transparent to the user). It is NOT keychain-protected, deliberately — see+ * PC/CLAUDE.md §6.5 OAuth section for the reasoning (portability + no OS-keystore dependency+ * trade-off the product owner accepted).+ *+ * What this protects against:+ * - Files accidentally syncing to a cloud backup that runs OCR / text indexing on them.+ * - Logging / crash-dump capture that incidentally reads the JSON.+ * - Hand-inspecting the file in a text editor.+ * - Random other apps reading `<uid>/local/config/` via filesystem permission slip-ups.+ *+ * What this does NOT protect against:+ * - An attacker who has both the disk contents AND the Orkas binary (the derivation function+ * is in source code → key is recoverable from `uid` alone).+ * - Targeted forensic recovery from a stolen device.+ *+ * Anyone needing the stronger guarantee should adopt keychain-backed storage; that's a separate+ * Phase 2 work item.+ *+ * File layout written to disk:+ *+ * `ORKVAULT1` (8 ASCII bytes) || [12B IV] || [16B GCM tag] || ciphertext+ *+ * The whole thing is base64-encoded so the file remains text (easier to ship + back up).+ */+import * as crypto from 'node:crypto';++const MAGIC = Buffer.from('ORKVAULT1');+const ITER = 200_000;+const KEY_LEN = 32;+const IV_LEN = 12;+const TAG_LEN = 16;++// Hardcoded compile-time salt. NOT a secret in any meaningful sense (it's in source) — just a+// per-app constant so a leaked encrypted file from one Orkas-derivative app can't be decrypted+// by another Orkas-derivative re-using uid alone.+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);+ return k;+}++export function isEncryptedPayload(text: string): boolean {+ // Cheap probe — anything that doesn't decode to our magic header is treated as plaintext.+ if (!text) return false;+ const head = text.slice(0, 12);+ try {+ const bytes = Buffer.from(head, 'base64');+ return bytes.length >= MAGIC.length && bytes.subarray(0, MAGIC.length).equals(MAGIC);+ } catch {+ return false;+ }+}++export function encrypt(uid: string, plaintext: string): string {+ if (!uid) throw new Error('crypto-vault: uid required');+ const key = _deriveKey(uid);+ 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()]);+ const tag = cipher.getAuthTag();+ const blob = Buffer.concat([MAGIC, iv, tag, ct]);+ return blob.toString('base64');+}++export function decrypt(uid: string, b64: string): string {+ if (!uid) throw new Error('crypto-vault: uid 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 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/renderer/index.html b/src/renderer/index.htmlindex 1e06a1a2..11c7115e 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -29,6 +29,7 @@<button class="sidebar-btn primary" id="new-chat-btn" data-i18n="sidebar.new_chat">Commander</button><button class="sidebar-btn" id="agents-btn" data-i18n="sidebar.agents">Agents</button><button class="sidebar-btn" id="skills-btn" data-i18n="sidebar.skills">Skills</button>+ <button class="sidebar-btn" id="connectors-btn" data-i18n="sidebar.connectors">Connectors</button><button class="sidebar-btn" id="contexts-btn" data-i18n="sidebar.contexts">Knowledge</button><button class="sidebar-btn" id="apps-btn" data-i18n="sidebar.apps">My Apps</button></div>@@ -320,6 +321,10 @@<div class="agents-detail-label" data-i18n="agents.label_workflow">Workflow</div><div class="agents-detail-workflow markdown-body" id="agents-detail-workflow" contenteditable="false"></div></div>+ <div class="agents-detail-section" id="agents-detail-connectors-section">+ <div class="agents-detail-label" data-i18n="agents.label_connectors">Connectors</div>+ <div class="agents-detail-connectors" id="agents-detail-connectors"></div>+ </div></div></div></div>@@ -422,6 +427,26 @@</div></section>+ <!-- Connectors (MCP-based, curated catalog) -->+ <section class="panel" id="panel-connectors">+ <div class="connectors-grid-view" id="connectors-grid-view">+ <div class="connectors-grid-header">+ <div class="connectors-grid-title" data-i18n="connectors.title">Connectors</div>+ </div>+ <div class="connectors-grid-scroll">+ <div class="connectors-group" id="connectors-group-connected" style="display:none">+ <div class="connectors-group-label" data-i18n="connectors.group.connected">Connected</div>+ <div class="connectors-grid" id="connectors-grid-connected"></div>+ </div>+ <div class="connectors-group" id="connectors-group-available" style="display:none">+ <div class="connectors-group-label" data-i18n="connectors.group.available">Available</div>+ <div class="connectors-grid" id="connectors-grid-available"></div>+ </div>+ <div class="connectors-empty empty" id="connectors-empty" style="display:none" data-i18n="connectors.empty">No connectors available.</div>+ </div>+ </div>+ </section>+<!-- Knowledge base --><section class="panel" id="panel-contexts"><div class="contexts-layout">@@ -606,14 +631,7 @@<div class="settings-group-title" data-i18n="settings.language.title">语言 / Language</div></div><div class="settings-row" id="settings-language-row">- <label class="settings-lang-opt">- <input type="radio" name="settings-language" value="zh" />- <span data-i18n="settings.language.zh">简体中文</span>- </label>- <label class="settings-lang-opt">- <input type="radio" name="settings-language" value="en" />- <span data-i18n="settings.language.en">English</span>- </label>+ <div class="ai-select" id="settings-language-select"></div></div></div>@@ -999,6 +1017,7 @@<script src="./modules/plan-rail.js"></script><script src="./modules/queue-draft.js"></script><script src="./modules/skills.js"></script>+ <script src="./modules/connectors.js"></script><script src="./modules/contexts.js"></script><script src="./modules/kb-picker.js"></script><script src="./modules/search.js"></script>diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 6c034b31..475ea734 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -25,8 +25,25 @@"sidebar.new_chat": "Commander","sidebar.agents": "Agents","sidebar.skills": "Skills",+ "sidebar.connectors": "Connectors","sidebar.apps": "My Apps","sidebar.contexts": "Knowledge",+ "connectors.title": "Connectors",+ "connectors.group.connected": "Connected",+ "connectors.group.available": "Available",+ "connectors.empty": "No connectors available.",+ "connectors.action.connect": "Connect",+ "connectors.action.disconnect": "Disconnect",+ "connectors.action.unavailable": "Coming soon",+ "connectors.confirm_disconnect_title": "Disconnect \"{name}\"",+ "connectors.confirm_disconnect_msg": "Tools provided by this connector will no longer be available.",+ "connectors.status.error": "Error",+ "connectors.errors.connect_failed": "Authorization failed",+ "connectors.errors.remove_failed": "Uninstall failed",+ "common.save": "Save",+ "common.loading": "Loading…",+ "agents.label_connectors": "Allowed connectors",+ "agents.connectors_empty": "No connectors installed. Add one in the Connectors tab.","sidebar.conversations": "Conversations","sidebar.conv_empty": "No conversations yet","sidebar.projects": "Projects",@@ -221,7 +238,7 @@"skills.empty": "No skills yet","skills.use": "Use","skills.edit": "Edit",- "skills.delete": "Delete",+ "skills.delete": "Uninstall","skills.use_tooltip": "Use this skill","skills.more_actions": "More actions","skills.back": "Back to skills",@@ -262,6 +279,11 @@"skills.save_failed": "Save failed","skills.delete_confirm": "Delete the skill \"{name}\" and all its files?","skills.delete_failed_with": "Delete failed: {reason}",+ "skills.delete_confirm": "Uninstall the skill \"{name}\" and all its files?",+ "skills.delete_failed_with": "Uninstall failed: {reason}",+ "skills.promote_to_builtin": "Make built-in (dev)",+ "skills.promote_confirm": "Promote the custom skill \"{name}\" to built-in? This writes to both src/builtin and data/builtin and removes the custom copy.",+ "skills.promote_failed_with": "Promote to built-in failed: {reason}","agents.title": "Agents","agents.create_btn": "+ Create","agents.more_btn": "More",@@ -273,7 +295,7 @@"agents.use_tooltip": "Use this agent","agents.more_actions": "More actions","agents.edit": "Edit",- "agents.delete": "Delete",+ "agents.delete": "Uninstall","agents.label_desc": "Summary","agents.label_runtime": "External agent","agents.label_workflow": "Workflow",@@ -299,6 +321,12 @@"agents.delete_confirm": "Delete this agent? Related conversations will also be removed.","agents.delete_failed": "Delete failed","agents.delete_failed_with": "Delete failed: {reason}",+ "agents.delete_confirm": "Uninstall this agent? Related conversations will also be removed.",+ "agents.delete_failed": "Uninstall failed",+ "agents.delete_failed_with": "Uninstall failed: {reason}",+ "agents.promote_to_builtin": "Make built-in (dev)",+ "agents.promote_confirm": "Promote the custom agent \"{name}\" to built-in? Only agent.json is copied to src/builtin and data/builtin (meta/ and self-evolved skills/ are dropped); the custom copy is removed.",+ "agents.promote_failed_with": "Promote to built-in failed: {reason}","agents.edit_chat_empty": "Tell me how you'd like to adjust this agent","agents.clear_confirm": "Clear the edit chat for this agent?","agents.agent_not_found": "Agent not found",@@ -541,8 +569,6 @@"settings.clear_all_convs.success": "Cleared {count} conversation(s).","settings.clear_all_convs.failed": "Clear-all failed: {message}","settings.language.title": "语言 / Language",- "settings.language.zh": "简体中文",- "settings.language.en": "English","settings.add_auth_title": "Add model authorization","settings.add_auth_sub": "Pick a provider and model, then add an API key or OAuth account.","settings.provider": "Provider",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex 43ae9ebd..92322e70 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -25,8 +25,25 @@"sidebar.new_chat": "指挥官","sidebar.agents": "智能体","sidebar.skills": "技能库",+ "sidebar.connectors": "连接器","sidebar.apps": "我的应用","sidebar.contexts": "知识库",+ "connectors.title": "连接器",+ "connectors.group.connected": "已连接",+ "connectors.group.available": "可用",+ "connectors.empty": "暂无可用连接器。",+ "connectors.action.connect": "连接",+ "connectors.action.disconnect": "断开",+ "connectors.action.unavailable": "敬请期待",+ "connectors.confirm_disconnect_title": "断开「{name}」",+ "connectors.confirm_disconnect_msg": "断开后该连接器提供的工具将不再可用。",+ "connectors.status.error": "异常",+ "connectors.errors.connect_failed": "授权失败",+ "connectors.errors.remove_failed": "卸载失败",+ "common.save": "保存",+ "common.loading": "加载中…",+ "agents.label_connectors": "可用连接器",+ "agents.connectors_empty": "尚未安装任何连接器。请在「连接器」tab 添加。","sidebar.conversations": "对话记录","sidebar.conv_empty": "暂无对话","sidebar.projects": "项目",@@ -221,7 +238,7 @@"skills.empty": "暂无技能","skills.use": "使用","skills.edit": "编辑",- "skills.delete": "删除",+ "skills.delete": "卸载","skills.use_tooltip": "使用此技能","skills.more_actions": "更多操作","skills.back": "返回技能库",@@ -262,6 +279,11 @@"skills.save_failed": "保存失败","skills.delete_confirm": "确认删除技能 \"{name}\" 及其所有文件?","skills.delete_failed_with": "删除失败:{reason}",+ "skills.delete_confirm": "确认卸载技能 \"{name}\" 及其所有文件?",+ "skills.delete_failed_with": "卸载失败:{reason}",+ "skills.promote_to_builtin": "设为内置(开发)",+ "skills.promote_confirm": "确认把自定义技能 \"{name}\" 提升为内置?会同步写入 src/builtin 与 data/builtin,并删除原自定义目录。",+ "skills.promote_failed_with": "提升为内置失败:{reason}","agents.title": "智能体","agents.create_btn": "+ 创建","agents.more_btn": "更多",@@ -273,7 +295,7 @@"agents.use_tooltip": "使用此智能体","agents.more_actions": "更多操作","agents.edit": "编辑",- "agents.delete": "删除",+ "agents.delete": "卸载","agents.label_desc": "简介","agents.label_runtime": "外接智能体","agents.label_workflow": "工作流程",@@ -299,6 +321,12 @@"agents.delete_confirm": "确认删除这个智能体?相关对话会一并删除。","agents.delete_failed": "删除失败","agents.delete_failed_with": "删除失败:{reason}",+ "agents.delete_confirm": "确认卸载这个智能体?相关对话会一并删除。",+ "agents.delete_failed": "卸载失败",+ "agents.delete_failed_with": "卸载失败:{reason}",+ "agents.promote_to_builtin": "设为内置(开发)",+ "agents.promote_confirm": "确认把自定义智能体 \"{name}\" 提升为内置?只复制 agent.json 到 src/builtin 与 data/builtin(meta/ 与自演化 skills/ 会丢弃),并删除原自定义目录。",+ "agents.promote_failed_with": "提升为内置失败:{reason}","agents.edit_chat_empty": "跟我说你想怎么调整这个智能体","agents.clear_confirm": "确认清空当前智能体的编辑对话记录?","agents.agent_not_found": "智能体不存在",@@ -541,8 +569,6 @@"settings.clear_all_convs.success": "已清空 {count} 条对话。","settings.clear_all_convs.failed": "清空失败:{message}","settings.language.title": "语言 / Language",- "settings.language.zh": "简体中文",- "settings.language.en": "English","settings.add_auth_title": "添加模型授权","settings.add_auth_sub": "选择提供商和模型,然后添加一个 API Key 或 OAuth 账号。","settings.provider": "提供商",diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex 3dfa4464..0c643cbc 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -573,9 +573,74 @@ function _renderAgentDetail(agent, editing) {}_renderAgentEnabledButton({ id: agent.agent_id, enabled: agent.enabled !== false });+ _renderAgentConnectorsSection(agent, editing);+_toggleAgentFieldEditable(editing);}+async function _renderAgentConnectorsSection(agent, editing) {+ const section = document.getElementById('agents-detail-connectors-section');+ const slot = document.getElementById('agents-detail-connectors');+ if (!section || !slot) return;+ // Hidden for CLI runtime agents (they don't go through the in-process AgentRunner that+ // injects connector tools).+ const isCliRuntime = !!(agent.runtime && agent.runtime.kind === 'cli');+ if (isCliRuntime) { section.style.display = 'none'; return; }+ section.style.display = '';++ let list = [];+ try {+ const res = await window.orkas.invoke('connectors.list', {});+ if (res && res.ok && Array.isArray(res.instances)) list = res.instances;+ } catch (_err) { /* leave list empty */ }++ const enabled = new Set(Array.isArray(agent.enabled_connectors) ? agent.enabled_connectors : []);+ const canEdit = agent.source === 'custom' || (agent.source === 'builtin' && typeof isDevMode === 'function' && false);++ if (!list.length) {+ slot.innerHTML = `<div class="muted">${escapeHtml(t('agents.connectors_empty') || 'No connectors installed. Add one in the Connectors tab.')}</div>`;+ return;+ }++ slot.innerHTML = '';+ for (const inst of list) {+ const row = document.createElement('label');+ row.className = 'agent-connector-row';+ const checked = enabled.has(inst.id);+ const status = (inst.status && inst.status.kind) || 'disconnected';+ row.innerHTML = `+ <input type="checkbox" class="agent-connector-toggle" ${checked ? 'checked' : ''} ${(canEdit && !editing) ? '' : 'disabled'} />+ <span class="connector-dot connector-dot-${status}"></span>+ <span class="agent-connector-name"></span>+ <span class="agent-connector-id muted"></span>+ `;+ row.querySelector('.agent-connector-name').textContent = inst.display_name || inst.id;+ row.querySelector('.agent-connector-id').textContent = inst.id;+ const cb = row.querySelector('.agent-connector-toggle');+ cb.addEventListener('change', async () => {+ if (cb.checked) enabled.add(inst.id);+ else enabled.delete(inst.id);+ try {+ const res = await window.orkas.invoke('agents.update', {+ agent_id: agent.agent_id,+ updates: { enabled_connectors: Array.from(enabled) },+ });+ if (!res || !res.ok) {+ cb.checked = !cb.checked;+ if (cb.checked) enabled.add(inst.id); else enabled.delete(inst.id);+ uiAlert((res && res.error) || t('agents.update_failed') || 'Update failed');+ } else if (res.agent) {+ agent.enabled_connectors = res.agent.enabled_connectors;+ }+ } catch (err) {+ cb.checked = !cb.checked;+ uiAlert((err && err.message) || 'Update failed');+ }+ });+ slot.appendChild(row);+ }+}+/** Render the runtime control in the detail body.** The runtime "kind" is locked at create time:diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.jsindex eb3d6776..9e2093ba 100644--- a/src/renderer/modules/boot.js+++ b/src/renderer/modules/boot.js@@ -143,6 +143,7 @@ function setView(view, cid, opts = {}) {const panelId = view === 'new-chat' ? 'panel-new-chat': view === 'agents' ? 'panel-agents': view === 'skills' ? 'panel-skills'+ : view === 'connectors' ? 'panel-connectors': view === 'contexts' ? 'panel-contexts': view === 'apps' ? 'panel-apps': view === 'settings' ? 'panel-settings'@@ -154,6 +155,7 @@ function setView(view, cid, opts = {}) {document.getElementById('new-chat-btn').classList.toggle('active', view === 'new-chat');document.getElementById('agents-btn').classList.toggle('active', view === 'agents');document.getElementById('skills-btn').classList.toggle('active', view === 'skills');+ document.getElementById('connectors-btn')?.classList.toggle('active', view === 'connectors');document.getElementById('contexts-btn')?.classList.toggle('active', view === 'contexts');document.getElementById('apps-btn')?.classList.toggle('active', view === 'apps');document.getElementById('settings-btn')?.classList.toggle('active', view === 'settings');@@ -232,6 +234,10 @@ function setView(view, cid, opts = {}) {currentCid = null;// Same reasoning as the agents branch above.loadSkills(true);+ } else if (view === 'connectors') {+ currentCid = null;+ // Status flips during a session (server health, token expiry); always re-fetch on entry.+ if (typeof loadConnectors === 'function') loadConnectors();} else if (view === 'contexts') {currentCid = null;loadContexts();diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.jsnew file mode 100644index 00000000..747d4584--- /dev/null+++ b/src/renderer/modules/connectors.js@@ -0,0 +1,245 @@+// Connectors panel — curated OAuth-only catalog of MCP-based integrations.+//+// Layout: a single scrollable grid view with two stacked sections — "已连接" (Connected) on top,+// "可用" (Available) below. No tab switching; same shape as the Skills panel's+// Custom / Built-in split. Both groups hide themselves when empty.+//+// Click model: only the action buttons on a card are clickable. Clicking elsewhere on a card+// does nothing — users routinely hovered over cards to read descriptions and the old whole-card+// click handler was firing OAuth flows by accident. Buttons stop propagation as a defence in+// depth.+//+// OAuth flow UX: clicking "连接" just opens the system browser and returns control to the+// renderer's _runConnect Promise (which the main process resolves once the deep-link callback+// completes). **The card itself does NOT change state during the flow** — no "授权中" badge, no+// disabled button. The user can click "连接" again at any time; server-side startOAuth+// supersedes any prior pending flow, and the renderer surfaces only real errors (the+// "superseded" message is swallowed since it's caused by the user's own re-click).++const _connectorsLog = createLogger('connectors');++let _connectorsState = {+ catalog: [],+ instances: [],+ loading: false,+};++async function loadConnectors() {+ _connectorsState.loading = true;+ _renderConnectorsGrid();+ try {+ const [catRes, listRes] = await Promise.all([+ window.orkas.invoke('connectors.catalog', {}),+ window.orkas.invoke('connectors.list', {}),+ ]);+ _connectorsState.catalog = (catRes && catRes.ok && Array.isArray(catRes.catalog)) ? catRes.catalog : [];+ _connectorsState.instances = (listRes && listRes.ok && Array.isArray(listRes.instances)) ? listRes.instances : [];+ } catch (err) {+ _connectorsLog.warn('list failed', { error: err && err.message });+ } finally {+ _connectorsState.loading = false;+ _renderConnectorsGrid();+ }+}++function _instanceById(id) {+ return _connectorsState.instances.find((i) => i.id === id) || null;+}++function _renderConnectorsGrid() {+ const gridView = document.getElementById('connectors-grid-view');+ if (!gridView) return;+ gridView.style.display = '';++ const groupConn = document.getElementById('connectors-group-connected');+ const groupAvail = document.getElementById('connectors-group-available');+ const gridConn = document.getElementById('connectors-grid-connected');+ const gridAvail = document.getElementById('connectors-grid-available');+ const empty = document.getElementById('connectors-empty');++ // 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 (inst && inst.status && inst.status.kind === 'connected') {+ connectedItems.push({ entry, instance: inst });+ } else {+ availableItems.push({ entry, instance: inst });+ }+ }+ // A→Z within each group (CLAUDE.md §8 inventory ordering).+ const cmp = (a, b) => (a.entry.display_name || '').localeCompare(b.entry.display_name || '', undefined, { sensitivity: 'base', numeric: true });+ connectedItems.sort(cmp);+ availableItems.sort(cmp);++ // Render each group.+ gridConn.innerHTML = '';+ for (const it of connectedItems) gridConn.appendChild(_renderCatalogCard(it.entry, it.instance));+ groupConn.style.display = connectedItems.length ? '' : 'none';++ gridAvail.innerHTML = '';+ for (const it of availableItems) gridAvail.appendChild(_renderCatalogCard(it.entry, it.instance));+ groupAvail.style.display = availableItems.length ? '' : 'none';++ if (_connectorsState.loading && !_connectorsState.catalog.length) {+ empty.style.display = '';+ empty.textContent = t('common.loading');+ } else if (!connectedItems.length && !availableItems.length) {+ empty.style.display = '';+ empty.textContent = t('connectors.empty');+ } else {+ empty.style.display = 'none';+ }+}++function _renderCatalogCard(entry, instance) {+ const e = entry || _entryFromInstance(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');++ const card = document.createElement('div');+ card.className = 'connector-card';+ 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.+ 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>`;+ } 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>`;+ }++ // Secondary line: account label when connected, error msg when errored, none otherwise.+ let secondaryHtml = '';+ if (errorMsg) {+ secondaryHtml = '<div class="connector-card-error"></div>';+ } else if (accountLabel) {+ secondaryHtml = '<div class="connector-card-account muted"></div>';+ }++ card.innerHTML = `+ <div class="connector-card-top">+ ${iconHtml}+ <div class="connector-card-headline">+ <div class="connector-card-name"></div>+ ${secondaryHtml}+ </div>+ </div>+ <div class="connector-card-desc muted"></div>+ <div class="connector-card-foot">${action}</div>+ `;+ card.querySelector('.connector-card-name').textContent = e.display_name;+ card.querySelector('.connector-card-desc').textContent = desc;+ if (errorMsg) {+ card.querySelector('.connector-card-error').textContent = `${t('connectors.status.error')}: ${errorMsg}`;+ } else if (accountLabel) {+ card.querySelector('.connector-card-account').textContent = accountLabel;+ }++ card.querySelectorAll('button[data-act]').forEach((btn) => {+ btn.addEventListener('click', (ev) => {+ ev.stopPropagation();+ const act = btn.dataset.act;+ if (act === 'connect') _runConnect(e);+ else if (act === 'disconnect') _quickDisconnect(e, instance);+ });+ });+ return card;+}++function _entryFromInstance(instance) {+ return {+ id: instance.id,+ display_name: instance.display_name || instance.id,+ description_zh: '',+ description_en: '',+ };+}++async function _quickDisconnect(entry, instance) {+ const id = (instance && instance.id) || entry.id;+ const name = (instance && instance.display_name) || entry.display_name || 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;+ try {+ const res = await window.orkas.invoke('connectors.remove', { id });+ if (!res || !res.ok) {+ uiAlert((res && res.error) || t('connectors.errors.remove_failed'));+ return;+ }+ await loadConnectors();+ } catch (err) {+ uiAlert((err && err.message) || t('connectors.errors.remove_failed'));+ }+}++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.+ try {+ const res = await window.orkas.invoke('connectors.start_oauth', { catalog_id: entry.id });+ if (res && res.ok && res.instance) {+ // Refresh state + re-render the grid. The new instance shows up in the "已连接" group.+ await loadConnectors();+ } else if (res && !res.ok) {+ const msg = (res.error || '').toLowerCase();+ if (!msg.includes('superseded') && !msg.includes('cancelled')) {+ uiAlert(res.error || t('connectors.errors.connect_failed'));+ }+ await loadConnectors();+ }+ } catch (err) {+ const msg = ((err && err.message) || '').toLowerCase();+ if (!msg.includes('superseded') && !msg.includes('cancelled')) {+ uiAlert((err && err.message) || t('connectors.errors.connect_failed'));+ }+ await loadConnectors();+ }+}++function escapeHtml(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''',+ })[c]);+}++window.addEventListener('i18n-change', () => {+ if (currentView === 'connectors') _renderConnectorsGrid();+});++// only consumer is the connectors panel itself, but registering at module load lets future+// background events (token expiry notifications etc.) refresh the panel automatically.+if (window.orkas && typeof window.orkas.on === 'function') {+ try {+ window.orkas.on('connectors:changed', () => {+ if (currentView === 'connectors') loadConnectors();+ });+ } catch (_err) { /* event not supported; harmless */ }+}diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.jsindex 12f5b071..d393f6e5 100644--- a/src/renderer/modules/settings.js+++ b/src/renderer/modules/settings.js@@ -232,20 +232,29 @@ function _settingsRenderDataRoot() {}}-// ── Language radio (zh / en) ──-// Bound once; `loadSettings` just re-syncs the checked state each time the-// panel is opened so the radio reflects whatever setLang() last persisted.--let _settingsLanguageBound = false;+// ── Language dropdown (zh / en) ──+// Bound once on first panel open; `loadSettings` then calls _settingsSyncLanguageRadio()+// to re-sync the dropdown's current value with whatever setLang() last persisted.+// Option labels are each language's autonym (本族语自称), intentionally NOT routed+// through t() — a Chinese user picking "English" should see "English", not the+// translation of "English" in the current UI language.++let _settingsLanguageSel = null; // _aiSelectMount api++const _SETTINGS_LANG_OPTIONS = [+ { value: 'zh', label: '简体中文' },+ { value: 'en', label: 'English' },+];function _settingsBindLanguageOnce() {- if (_settingsLanguageBound) return;- const row = document.getElementById('settings-language-row');- if (!row) return;- row.addEventListener('change', async (e) => {- const target = e.target;- if (!target || target.name !== 'settings-language') return;- const next = target.value;+ if (_settingsLanguageSel) return;+ const el = document.getElementById('settings-language-select');+ if (!el) return;+ _settingsLanguageSel = _aiSelectMount(el, {+ options: _SETTINGS_LANG_OPTIONS,+ value: (typeof getLang === 'function') ? getLang() : 'en',+ });+ _settingsLanguageSel.onChange(async (next) => {if (next !== 'zh' && next !== 'en') return;try {await setLang(next);@@ -254,14 +263,12 @@ function _settingsBindLanguageOnce() {_settingsLog.warn('setLang failed', { error: (err && err.message) || String(err) });}});- _settingsLanguageBound = true;}function _settingsSyncLanguageRadio() {- const cur = typeof getLang === 'function' ? getLang() : 'en';- document.querySelectorAll('input[name="settings-language"]').forEach((el) => {- el.checked = (el.value === cur);- });+ // Function name kept for caller-side compatibility; semantics is now "sync dropdown value".+ const cur = (typeof getLang === 'function') ? getLang() : 'en';+ if (_settingsLanguageSel) _settingsLanguageSel.setValue(cur);}// ── Clear all conversations ──diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.jsindex 0881b4ae..4904d407 100644--- a/src/renderer/modules/state.js+++ b/src/renderer/modules/state.js@@ -154,6 +154,7 @@ function bindStaticHandlers() {document.getElementById('new-chat-btn').addEventListener('click', () => setView('new-chat'));document.getElementById('agents-btn').addEventListener('click', () => setView('agents'));document.getElementById('skills-btn').addEventListener('click', () => setView('skills'));+ document.getElementById('connectors-btn')?.addEventListener('click', () => setView('connectors'));document.getElementById('apps-btn')?.addEventListener('click', () => setView('apps'));document.getElementById('contexts-btn').addEventListener('click', () => setView('contexts'));document.getElementById('settings-btn')?.addEventListener('click', () => setView('settings'));diff --git a/src/renderer/style.css b/src/renderer/style.cssindex a44887af..b91cd624 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -6715,9 +6715,11 @@ body.model-not-configured .main-content { flex-direction: column; }.marketplace-detail-body > .agents-detail-body,.marketplace-detail-body > .skills-detail-content { flex: 1; min-height: 0; }.marketplace-detail-loading {+ flex: 1;display: flex;flex-direction: column;align-items: center;+ justify-content: center;gap: 10px;padding: 48px 20px;}@@ -7033,3 +7035,238 @@ body.model-not-configured .main-content { flex-direction: column; }border-radius: 6px;font-size: 13px;}+/* ─── Connectors panel ─── */+/* The `.panel` base rule already sets display:none → flex toggle via `.active`; do NOT+ override `#panel-connectors` with `display: flex`, that breaks the setView() gating+ (id selector beats the class rule → panel stays visible regardless of `.active`). */+.connectors-grid-view, .connectors-detail-view {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 0;+}+.connectors-grid-header {+ padding: 18px 20px 14px;+ border-bottom: 1px solid var(--border);+ background: #fff;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ flex-shrink: 0;+}+.connectors-grid-title { font-size: 16px; font-weight: 600; color: var(--text); }+.connectors-grid-tabs {+ display: flex;+ gap: 16px;+ padding: 12px 20px 0;+ border-bottom: 1px solid var(--border);+ background: #fff;+ flex-shrink: 0;+}+.connectors-tab {+ background: transparent;+ border: 0;+ padding: 8px 4px;+ cursor: pointer;+ font-size: 13px;+ color: var(--text-muted, #6b7280);+ border-bottom: 2px solid transparent;+}+.connectors-tab.is-active { color: var(--text); border-bottom-color: #2563eb; }+.connectors-grid-scroll { flex: 1; overflow-y: auto; padding: 18px 24px 32px; }+.connectors-group { flex-shrink: 0; padding: 6px 0; }+.connectors-group-label {+ padding: 12px 4px 6px;+ font-size: 11px;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.6px;+ color: #9ca3af;+}+.connectors-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));+ gap: 16px;+ padding: 8px 0 16px;+}+.connectors-empty { padding: 32px; text-align: center; }+.connector-card {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 16px;+ background: #fff;+ border: 1px solid var(--border);+ border-radius: 12px;+ cursor: pointer;+ transition: border-color 0.12s, box-shadow 0.12s;+ min-height: 152px;+}+.connector-card:hover {+ border-color: rgba(37, 99, 235, 0.45);+ box-shadow: 0 4px 16px rgba(15, 23, 42, 0.06);+}+.connector-card-top { display: flex; align-items: center; gap: 10px; }+.connector-card-icon {+ width: 40px;+ height: 40px;+ border-radius: 10px;+ display: flex;+ align-items: center;+ justify-content: center;+ color: #fff;+ font-size: 13px;+ font-weight: 600;+ flex-shrink: 0;+}+.connector-card-icon.is-svg {+ background: #fff;+ border: 1px solid rgba(15, 23, 42, 0.08);+ padding: 6px;+}+.connector-card-icon.is-svg svg {+ width: 100%;+ height: 100%;+ display: block;+}+.connector-card-icon.is-fallback {+ background: #6b7280;+}+.connector-card-headline { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }+.connector-card-name {+ font-size: 15px;+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.connector-card-account {+ font-size: 12px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.connector-card-error {+ font-size: 12px;+ color: #b91c1c;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.connector-card-desc {+ font-size: 12px;+ line-height: 1.5;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.connector-card-foot { margin-top: auto; display: flex; justify-content: flex-end; gap: 6px; align-items: center; }+.connector-card-foot .btn-link {+ background: transparent;+ border: none;+ color: var(--text-muted, #6b7280);+ text-decoration: underline;+ cursor: pointer;+ padding: 4px 8px;+}+.connector-card-foot .btn-link:hover { color: #2563eb; }++/* Tab count badge */+.connectors-tab { display: inline-flex; align-items: center; gap: 6px; }+.connectors-tab-count { font-size: 11px; }++/* Legacy dot retained for the agent detail toggle list */+.connector-dot {+ display: inline-block;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #9ca3af;+}+.connector-dot-connected { background: #10b981; }+.connector-dot-connecting { background: #f59e0b; }+.connector-dot-error { background: #ef4444; }++/* Detail view */+.connectors-detail-header {+ padding: 14px 20px;+ border-bottom: 1px solid var(--border);+ background: #fff;+ display: flex;+ align-items: center;+ gap: 12px;+ flex-shrink: 0;+}+.connectors-detail-title { flex: 1; font-size: 15px; font-weight: 600; }+.connectors-detail-actions { display: flex; gap: 8px; }+.connectors-detail-body { flex: 1; overflow-y: auto; padding: 20px 24px 32px; }+.connector-detail-row { display: flex; gap: 12px; padding: 6px 0; font-size: 13px; align-items: baseline; }+.connector-detail-section { margin-top: 18px; }+.connector-detail-section-title { font-size: 13px; font-weight: 600; margin-bottom: 8px; color: var(--text); }+.connector-tools-list { display: flex; flex-direction: column; gap: 4px; }+.connector-tool-row {+ display: grid;+ grid-template-columns: auto 200px 1fr;+ gap: 10px;+ align-items: baseline;+ padding: 6px 0;+ font-size: 13px;+ cursor: pointer;+ border-bottom: 1px solid #f3f4f6;+}+.connector-tool-name { font-family: ui-monospace, monospace; font-size: 12px; }+.connector-tool-desc { font-size: 12px; overflow: hidden; text-overflow: ellipsis; }++/* Connect / configure modal (minimal scoped styles for the connectors flow; if the project+ later introduces a shared .modal-overlay / .modal-card system, these can be retired). */+#connectors-connect-modal.modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(15, 23, 42, 0.45);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 1000;+}+#connectors-connect-modal .modal-card {+ width: min(520px, 92vw);+ max-height: 88vh;+ overflow: auto;+ background: #fff;+ border-radius: 12px;+ padding: 20px 24px;+ display: flex;+ flex-direction: column;+ gap: 16px;+}+#connectors-connect-modal .modal-title { font-size: 16px; font-weight: 600; }+#connectors-connect-modal .form-row { display: flex; flex-direction: column; gap: 6px; }+#connectors-connect-modal .form-row label { font-size: 12px; font-weight: 500; color: var(--text-muted, #6b7280); }+#connectors-connect-modal .form-row input,+#connectors-connect-modal .form-row select {+ font: inherit;+ padding: 6px 8px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: #fff;+}+#connectors-connect-modal .form-hint { font-size: 11px; display: inline-block; }+#connectors-connect-modal .modal-actions { display: flex; gap: 8px; justify-content: flex-end; }+.connectors-add-status { font-size: 12px; min-height: 18px; }++/* Per-agent connector toggle row inside the agent detail page */+.agent-connector-row {+ display: grid;+ grid-template-columns: auto auto 1fr auto;+ gap: 10px;+ align-items: center;+ padding: 8px 0;+ font-size: 13px;+ border-bottom: 1px solid #f3f4f6;+ cursor: pointer;+}+.agent-connector-name { color: var(--text); }+.agent-connector-id { font-family: ui-monospace, monospace; font-size: 11px; }diff --git a/test/main/model/core-agent/connector-meta-tools.test.ts b/test/main/model/core-agent/connector-meta-tools.test.tsnew file mode 100644index 00000000..d22c5fb2--- /dev/null+++ b/test/main/model/core-agent/connector-meta-tools.test.ts@@ -0,0 +1,532 @@+/**+ * Tests for the connector umbrella architecture: `getConnectorPromptBlock` (system-prompt+ * enumeration) + the two meta-tools (`list_connector_tools` / `call_connector_tool`). Covers+ * the actor-visibility matrix (commander vs. agent worker, the `enabled_connectors` whitelist,+ * the `enabled_subtools` instance filter), the empty-state contract (zero tools + empty block+ * when nothing visible), the discover-before-invoke contract, and MCP error propagation.+ *+ * `manager` and `agents` are mocked at the module level. The live MCP transport is never+ * spawned.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';++import type { ConnectorInstance, ToolSchema } from '../../../../src/main/features/connectors/types';++// ── Mocks ────────────────────────────────────────────────────────────────++type AgentMock = { agent_id: string; enabled_connectors?: string[] } | null;++const fixtures: {+ instances: ConnectorInstance[];+ agents: Record<string, AgentMock>;+ callTool: (uid: string, id: string, name: string, args: Record<string, unknown>) => Promise<unknown>;+} = {+ instances: [],+ agents: {},+ callTool: async () => 'OK',+};++vi.mock('../../../../src/main/features/connectors/manager', () => ({+ listInstances: (uid: string) => (uid ? fixtures.instances : []),+ callTool: (uid: string, id: string, name: string, args: Record<string, unknown>) =>+ fixtures.callTool(uid, id, name, args),+}));++vi.mock('../../../../src/main/features/agents', () => ({+ getAgent: async (agentId: string | null | undefined) =>+ (agentId ? fixtures.agents[agentId] ?? null : null),+}));++// Catalog stub: descriptions land in the rendered block. Test fixture covers Notion + GitHub+// (both used in NOTION_TOOLS / GITHUB_TOOLS); other ids return undefined → block falls back to+// display_name only.+vi.mock('../../../../src/main/features/connectors/catalog', () => ({+ findCatalogEntry: (id: string) => {+ if (id === 'notion') return { id, description_zh: '读写 Notion 页面', description_en: 'Read and write Notion pages.' };+ if (id === 'github') return { id, description_zh: '仓库 / Issue / PR / 代码搜索', description_en: 'Repos, issues, PRs, code search.' };+ return undefined;+ },+}));++vi.mock('../../../../src/main/i18n', () => ({+ getCurrentLang: () => 'en',+}));++vi.mock('../../../../src/main/logger', () => ({+ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }),+}));++// ── Helpers ──────────────────────────────────────────────────────────────++function makeInstance(overrides: Partial<ConnectorInstance> & { id: string; tools?: ToolSchema[] }): ConnectorInstance {+ const tools: ToolSchema[] = overrides.tools ?? [];+ return {+ id: overrides.id,+ display_name: overrides.display_name ?? overrides.id,+ transport: { kind: 'streamable-http', url: 'https://example.invalid/mcp' },+ enabled_subtools: overrides.enabled_subtools ?? null,+ tools_cache: tools,+ tools_cached_at: 0,+ status: overrides.status ?? { kind: 'connected', since: 0 },+ created_at: '2026-05-14T00:00:00.000Z',+ updated_at: '2026-05-14T00:00:00.000Z',+ ...(overrides.icon ? { icon: overrides.icon } : {}),+ ...(overrides.oauth_grant ? { oauth_grant: overrides.oauth_grant } : {}),+ ...(overrides.dcr_client ? { dcr_client: overrides.dcr_client } : {}),+ };+}++const NOTION_TOOLS: ToolSchema[] = [+ {+ name: 'search',+ description: 'Search Notion pages by query.',+ input_schema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },+ },+ {+ name: 'create_page',+ description: 'Create a new page.',+ input_schema: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] },+ },+];++const GITHUB_TOOLS: ToolSchema[] = [+ {+ name: 'list_repos',+ description: 'List the authenticated user\'s repos.',+ input_schema: { type: 'object', properties: {} },+ },+];++const UID = 'u-meta-001';++beforeEach(() => {+ fixtures.instances = [];+ fixtures.agents = {};+ fixtures.callTool = async () => 'OK';+ vi.resetModules();+});++async function loadModule() {+ return import('../../../../src/main/model/core-agent/connector-meta-tools');+}++async function runTool(tool: { execute: (input: any, ctx: any) => Promise<any> }, input: Record<string, unknown> = {}) {+ return tool.execute(input, { workingDir: '.', signal: undefined } as any);+}++// ── connectorExposureFromSessionId (the runner.ts session-kind gate) ────++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 () => {+ const { connectorExposureFromSessionId } = await import('../../../../src/main/model/core-agent/runner');+ expect(connectorExposureFromSessionId('D69594E0-CF31-424C-9318-30231197E3A9-gconv-ac5559863d42')).toBe('tools+block');+ });++ it('matches gmember with a UUID-shaped uid + dashed cid + dashed aid', 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');+ });++ it('matches agent-edit with a UUID-shaped uid', 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');+ });++ 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();+ });+});++// ── createConnectorMetaTools shape (now async + conditional) ────────────++describe('createConnectorMetaTools', () => {+ it('returns the two 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 });+ expect(tools.map((t) => t.name)).toEqual([+ 'list_connector_tools',+ 'call_connector_tool',+ ]);+ });++ it('returns [] when no connector is visible (commander, no instances installed)', async () => {+ fixtures.instances = [];+ const { createConnectorMetaTools } = await loadModule();+ expect(await createConnectorMetaTools({ userId: UID })).toEqual([]);+ });++ it('returns [] when agent worker has empty enabled_connectors (matches the prompt-block omission)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.agents = { 'a1': { agent_id: 'a1', enabled_connectors: [] } };+ const { createConnectorMetaTools } = await loadModule();+ expect(await createConnectorMetaTools({ userId: UID, agentId: 'a1' })).toEqual([]);+ });++ it('returns [] when uid empty (no scope)', async () => {+ const { createConnectorMetaTools } = await loadModule();+ expect(await createConnectorMetaTools({ userId: '' })).toEqual([]);+ });+});++// ── getConnectorPromptBlock ─────────────────────────────────────────────++describe('getConnectorPromptBlock', () => {+ it('renders one line per connector with id + display_name + catalog description (en)', async () => {+ fixtures.instances = [+ makeInstance({ id: 'notion', display_name: 'Notion', tools: NOTION_TOOLS }),+ makeInstance({ id: 'github', display_name: 'GitHub', tools: GITHUB_TOOLS }),+ ];+ const { getConnectorPromptBlock } = await loadModule();+ const block = await getConnectorPromptBlock(UID, undefined);+ expect(block).toContain('## Connectors');+ expect(block).toContain('**notion** — Notion: Read and write Notion pages.');+ expect(block).toContain('**github** — GitHub: Repos, issues, PRs, code search.');+ });++ it('does NOT include the protocol-teaching header paragraph (per-role chat prompts teach that)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { getConnectorPromptBlock } = await loadModule();+ const block = await getConnectorPromptBlock(UID, undefined);+ expect(block).not.toContain('list_connector_tools');+ expect(block).not.toContain('call_connector_tool');+ expect(block).not.toMatch(/don't guess|list first/i);+ });++ it('does NOT include action counts (filler — model finds out via list_connector_tools)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { getConnectorPromptBlock } = await loadModule();+ const block = await getConnectorPromptBlock(UID, undefined);+ expect(block).not.toMatch(/\d+ actions?/);+ });++ it('appends "(account: ...)" only when the OAuth grant carries an account_label', async () => {+ fixtures.instances = [+ makeInstance({+ id: 'notion',+ tools: NOTION_TOOLS,+ oauth_grant: {+ access_token: 't',+ refresh_token: null,+ expires_at: null,+ scopes: [],+ token_type: 'Bearer',+ account_label: '[email protected]',+ },+ }),+ makeInstance({ id: 'github', tools: GITHUB_TOOLS }), // no oauth_grant+ ];+ const { getConnectorPromptBlock } = await loadModule();+ const block = await getConnectorPromptBlock(UID, undefined);+ expect(block).toContain('(account: [email protected])');+ // github line should not have a parenthetical account+ const githubLine = block.split('\n').find((l) => l.includes('**github**')) ?? '';+ expect(githubLine).not.toContain('account:');+ });++ it('omits status suffix on the healthy `connected` case (keeps lines short)', 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');+ });++ it('appends a status suffix only when not connected (lets the model surface the issue)', async () => {+ fixtures.instances = [+ makeInstance({ id: 'notion', tools: NOTION_TOOLS, status: { kind: 'disconnected' } }),+ ];+ 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);+ });++ it('falls back to display_name only when the catalog has no description (defensive)', async () => {+ // 'unknown_id' isn't in our findCatalogEntry mock → returns undefined+ fixtures.instances = [makeInstance({ id: 'unknown_id', display_name: 'Mystery Service', tools: [] })];+ const { getConnectorPromptBlock } = await loadModule();+ const block = await getConnectorPromptBlock(UID, undefined);+ expect(block).toContain('**unknown_id** — Mystery Service');+ expect(block).not.toContain(': '); // no description colon when fallback+ });++ it('respects the agent enabled_connectors whitelist (only allowed connectors appear)', async () => {+ fixtures.instances = [+ makeInstance({ id: 'notion', tools: NOTION_TOOLS }),+ makeInstance({ id: 'github', tools: GITHUB_TOOLS }),+ ];+ fixtures.agents = { 'a1': { agent_id: 'a1', enabled_connectors: ['notion'] } };+ const { getConnectorPromptBlock } = await loadModule();+ const block = await getConnectorPromptBlock(UID, 'a1');+ expect(block).toContain('**notion**');+ expect(block).not.toContain('**github**');+ });++ it('returns "" when no connector is visible (commander, none installed)', async () => {+ fixtures.instances = [];+ const { getConnectorPromptBlock } = await loadModule();+ expect(await getConnectorPromptBlock(UID, undefined)).toBe('');+ });++ it('returns "" when agent enabled_connectors is undefined (stricter than skill_list)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.agents = { 'a1': { agent_id: 'a1' } };+ const { getConnectorPromptBlock } = await loadModule();+ expect(await getConnectorPromptBlock(UID, 'a1')).toBe('');+ });++ it('returns "" when uid is empty', async () => {+ const { getConnectorPromptBlock } = await loadModule();+ expect(await getConnectorPromptBlock('', undefined)).toBe('');+ });+});++// ── list_connector_tools ────────────────────────────────────────────────++describe('list_connector_tools', () => {+ it('connected instance returns full tool schemas', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { createConnectorMetaTools } = await loadModule();+ const [listTools] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(listTools, { connector_id: 'notion' });+ expect(r.isError).toBeFalsy();+ expect(r.content).toContain('### search');+ expect(r.content).toContain('### create_page');+ expect(r.content).toContain('"query"');+ expect(r.content).toContain('"title"');+ });++ it('enabled_subtools whitelist filters the visible action list', async () => {+ fixtures.instances = [+ makeInstance({ id: 'notion', tools: NOTION_TOOLS, enabled_subtools: ['search'] }),+ ];+ const { createConnectorMetaTools } = await loadModule();+ const [listTools] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(listTools, { connector_id: 'notion' });+ expect(r.content).toContain('### search');+ expect(r.content).not.toContain('### create_page');+ });++ it('unknown connector_id → E_CONNECTOR_NOT_VISIBLE', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { createConnectorMetaTools } = await loadModule();+ const [listTools] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(listTools, { connector_id: 'slack' });+ expect(r.isError).toBe(true);+ 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.+ fixtures.instances = [+ makeInstance({ id: 'github', tools: GITHUB_TOOLS }),+ makeInstance({ id: 'notion', tools: NOTION_TOOLS, status: { kind: 'disconnected' } }),+ ];+ const { createConnectorMetaTools } = await loadModule();+ 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');+ });++ it('missing connector_id → E_BAD_INPUT', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { createConnectorMetaTools } = await loadModule();+ const [listTools] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(listTools, {});+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_BAD_INPUT');+ });++ it('respects agent whitelist at execution time (not just at build time)', async () => {+ fixtures.instances = [+ makeInstance({ id: 'notion', tools: NOTION_TOOLS }),+ makeInstance({ id: 'github', tools: GITHUB_TOOLS }),+ ];+ fixtures.agents = { 'a1': { agent_id: 'a1', enabled_connectors: ['notion'] } };+ const { createConnectorMetaTools } = await loadModule();+ const [listTools] = await createConnectorMetaTools({ userId: UID, agentId: 'a1' });+ const r = await runTool(listTools, { connector_id: 'github' });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');+ });+});++// ── call_connector_tool ─────────────────────────────────────────────────++describe('call_connector_tool', () => {+ it('routes a valid call to manager.callTool with verbatim args + stringifies the result', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ let received: { uid?: string; id?: string; name?: string; args?: Record<string, unknown> } = {};+ fixtures.callTool = async (uid, id, name, args) => {+ received = { uid, id, name, args };+ return { content: [{ type: 'text', text: 'page hits: 3' }] };+ };+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, {+ connector_id: 'notion',+ tool_name: 'search',+ args: { query: 'plan' },+ });+ expect(r.isError).toBeFalsy();+ expect(r.content).toBe('page hits: 3');+ expect(received).toEqual({ uid: UID, id: 'notion', name: 'search', args: { query: 'plan' } });+ });++ it('connector not in actor scope → E_CONNECTOR_NOT_VISIBLE (does not invoke manager.callTool)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ let calledManager = false;+ fixtures.callTool = async () => { calledManager = true; return ''; };+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'slack', tool_name: 'whatever', args: {} });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_CONNECTOR_NOT_VISIBLE');+ expect(calledManager).toBe(false);+ });++ it('tool_name not in tools_cache → E_TOOL_NOT_AVAILABLE (does not invoke manager.callTool)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ let calledManager = false;+ fixtures.callTool = async () => { calledManager = true; return ''; };+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'delete_universe', args: {} });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_TOOL_NOT_AVAILABLE');+ expect(calledManager).toBe(false);+ });++ it('tool_name muted by enabled_subtools → E_TOOL_NOT_AVAILABLE', async () => {+ fixtures.instances = [+ makeInstance({ id: 'notion', tools: NOTION_TOOLS, enabled_subtools: ['search'] }),+ ];+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'create_page', args: { title: 'x' } });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_TOOL_NOT_AVAILABLE');+ });++ it('MCP error from manager.callTool propagates with isError=true (not silently swallowed)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.callTool = async () => { throw new Error('upstream rate limited'); };+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'search', args: { query: 'x' } });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('upstream rate limited');+ });++ it('missing args object → E_BAD_INPUT', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'search' });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_BAD_INPUT');+ });++ it('missing connector_id → E_BAD_INPUT', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { tool_name: 'search', args: {} });+ expect(r.isError).toBe(true);+ expect(r.content).toContain('E_BAD_INPUT');+ });+});++// ── stringifyMcpResult (transitively, via call_connector_tool) ──────────++describe('stringifyMcpResult (via call_connector_tool)', () => {+ it('flattens MCP `content: [{type:"text", text}]` arrays', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.callTool = async () => ({+ content: [+ { type: 'text', text: 'first' },+ { type: 'text', text: 'second' },+ ],+ });+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'search', args: { query: 'x' } });+ expect(r.content).toBe('first\nsecond');+ });++ it('returns plain strings verbatim', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.callTool = async () => 'just a string';+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'search', args: { query: 'x' } });+ expect(r.content).toBe('just a string');+ });++ it('JSON-serialises non-text MCP shapes (image / structured data)', async () => {+ fixtures.instances = [makeInstance({ id: 'notion', tools: NOTION_TOOLS })];+ fixtures.callTool = async () => ({ content: [{ type: 'image', data: 'b64...' }] });+ const { createConnectorMetaTools } = await loadModule();+ const [, call] = await createConnectorMetaTools({ userId: UID });+ const r = await runTool(call, { connector_id: 'notion', tool_name: 'search', args: { query: 'x' } });+ expect(r.content).toContain('"type":"image"');+ });+});diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.tsindex 6f5545b7..59c7b14a 100644--- a/test/main/model/core-agent/tool-catalog.test.ts+++ b/test/main/model/core-agent/tool-catalog.test.ts@@ -47,6 +47,14 @@ function enumerateAllInjectedToolNames(): Set<string> {for (const t of createKbTools({ userId: 'testuid' })) names.add(t.name);names.add(createImageGenTool({ userId: 'testuid', cid: 'testcid' }).name);+ // Connector umbrella meta-tools: two fixed tools, only injected when ≥1 connector is visible+ // to the actor. Asserting presence in the catalog independent of runtime visibility — calling+ // the factory here would short-circuit to [] without a manager mock, defeating the drift+ // check. Per-connector MCP actions discovered at runtime are NOT enumerated (they vary+ // per-user / per-install — see tool-catalog.ts header).+ names.add('list_connector_tools');+ names.add('call_connector_tool');+return names;}