@myrialabs/clopen 0.4.47 → 0.4.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/backend/artifacts/project/sources.ts +1 -1
- package/backend/auth/auth-service.ts +52 -358
- package/backend/auth/onboarding.test.ts +2 -3
- package/backend/auth/permissions.test.ts +10 -20
- package/backend/auth/permissions.ts +4 -290
- package/backend/auth/rate-limiter.test.ts +8 -9
- package/backend/auth/rate-limiter.ts +0 -2
- package/backend/auth/tokens.ts +1 -8
- package/backend/bootstrap.ts +7 -0
- package/backend/chat/attachments.test.ts +88 -0
- package/backend/chat/attachments.ts +159 -0
- package/backend/chat/engine-handoff.test.ts +0 -2
- package/backend/chat/stream-manager.ts +62 -62
- package/backend/chat/turn-answer.test.ts +64 -0
- package/backend/chat/turn-answer.ts +125 -0
- package/backend/chat-apps/awaiting.test.ts +39 -0
- package/backend/chat-apps/awaiting.ts +49 -0
- package/backend/chat-apps/conversation.ts +746 -0
- package/backend/chat-apps/inbound.ts +324 -0
- package/backend/chat-apps/index.ts +309 -0
- package/backend/chat-apps/link-events.ts +20 -0
- package/backend/chat-apps/media.test.ts +62 -0
- package/backend/chat-apps/media.ts +208 -0
- package/backend/chat-apps/messages.test.ts +229 -0
- package/backend/chat-apps/messages.ts +365 -0
- package/backend/chat-apps/outbound.ts +243 -0
- package/backend/chat-apps/pairing.test.ts +45 -0
- package/backend/chat-apps/pairing.ts +74 -0
- package/backend/chat-apps/platforms/index.ts +20 -0
- package/backend/chat-apps/platforms/telegram.test.ts +35 -0
- package/backend/chat-apps/platforms/telegram.ts +191 -0
- package/backend/chat-apps/platforms/types.ts +114 -0
- package/backend/chat-apps/questions.ts +133 -0
- package/backend/chat-apps/runtime.ts +572 -0
- package/backend/chat-apps/storage.test.ts +201 -0
- package/backend/chat-apps/turns.test.ts +45 -0
- package/backend/chat-apps/turns.ts +208 -0
- package/backend/containers/pty.ts +3 -11
- package/backend/control/actions/accounts.ts +89 -0
- package/backend/control/actions/files.ts +116 -0
- package/backend/control/actions/models.ts +188 -0
- package/backend/control/actions/projects.ts +272 -0
- package/backend/control/actions/sessions.ts +280 -0
- package/backend/control/actions/skills.ts +111 -0
- package/backend/control/control.test.ts +169 -0
- package/backend/control/define.ts +20 -0
- package/backend/control/folders.test.ts +67 -0
- package/backend/control/index.ts +213 -0
- package/backend/control/invoke.ts +44 -0
- package/backend/control/links.ts +35 -0
- package/backend/control/paging.ts +26 -0
- package/backend/control/types.ts +117 -0
- package/backend/control/workspace.ts +127 -0
- package/backend/database/migrations/084_create_channel_links.ts +71 -0
- package/backend/database/migrations/085_add_home_projects.ts +36 -0
- package/backend/database/migrations/086_single_owner.test.ts +170 -0
- package/backend/database/migrations/086_single_owner.ts +418 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/channel-queries.ts +270 -0
- package/backend/database/queries/db-client-connection-queries.ts +18 -56
- package/backend/database/queries/file-share-queries.ts +5 -23
- package/backend/database/queries/git-identity-queries.ts +31 -42
- package/backend/database/queries/graph-queries.ts +1 -1
- package/backend/database/queries/index.ts +13 -1
- package/backend/database/queries/message-queries.test.ts +146 -0
- package/backend/database/queries/message-queries.ts +42 -1
- package/backend/database/queries/permission-set-queries.ts +1 -1
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
- package/backend/database/queries/project-queries.ts +50 -63
- package/backend/database/queries/session-queries.ts +28 -56
- package/backend/database/queries/ssh-connection-queries.ts +18 -41
- package/backend/db-client/integrations/projector.ts +0 -5
- package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
- package/backend/engine/adapters/claude/message-converter.ts +25 -2
- package/backend/engine/adapters/cline/message-converter.ts +0 -1
- package/backend/engine/adapters/cline/stream.ts +11 -15
- package/backend/engine/adapters/codex/message-converter.ts +0 -2
- package/backend/engine/adapters/copilot/message-converter.ts +1 -2
- package/backend/engine/adapters/cursor/message-converter.ts +0 -1
- package/backend/engine/adapters/opencode/message-converter.ts +2 -4
- package/backend/engine/adapters/opencode/stream.ts +11 -0
- package/backend/engine/adapters/parent-scope.test.ts +38 -0
- package/backend/engine/adapters/parent-scope.ts +44 -0
- package/backend/engine/adapters/pi/message-converter.ts +0 -1
- package/backend/engine/adapters/pi/stream.ts +4 -5
- package/backend/engine/adapters/qwen/message-converter.ts +0 -2
- package/backend/engine/bootstrap-default-engine.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +8 -1
- package/backend/engine/install-runner.ts +8 -17
- package/backend/files/file-shares.ts +20 -44
- package/backend/files/file-size-limit.ts +3 -3
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/git-executor.ts +25 -5
- package/backend/git/git-service.ts +420 -19
- package/backend/git/identity/credential-helper.test.ts +2 -7
- package/backend/git/identity/import-local.test.ts +11 -16
- package/backend/git/identity/import-local.ts +12 -12
- package/backend/git/identity/index.ts +10 -24
- package/backend/git/identity/resolve.ts +13 -14
- package/backend/git/identity/scope-config.ts +33 -28
- package/backend/git/identity/service.ts +44 -47
- package/backend/git/op-lock.test.ts +111 -0
- package/backend/git/op-lock.ts +180 -0
- package/backend/git/remote-sync.test.ts +249 -0
- package/backend/host/metrics.ts +1 -1
- package/backend/http/bearer-auth.ts +1 -2
- package/backend/http/files-download.test.ts +8 -9
- package/backend/http/files-download.ts +2 -2
- package/backend/http/files-shared.test.ts +62 -89
- package/backend/http/files-shared.ts +2 -2
- package/backend/http/files-upload.test.ts +3 -7
- package/backend/http/files-upload.ts +3 -3
- package/backend/http/notes-images.test.ts +15 -38
- package/backend/http/notes-images.ts +6 -8
- package/backend/http/ssh-sftp.ts +5 -10
- package/backend/index.ts +21 -7
- package/backend/integrations/accounts.ts +61 -3
- package/backend/integrations/index.ts +2 -2
- package/backend/integrations/registry/define.ts +15 -0
- package/backend/integrations/registry/index.ts +2 -0
- package/backend/integrations/registry/providers/telegram.ts +54 -0
- package/backend/integrations/registry/types.ts +21 -1
- package/backend/integrations/webhooks/gateway.ts +7 -6
- package/backend/integrations/webhooks/verify.test.ts +30 -0
- package/backend/integrations/webhooks/verify.ts +4 -0
- package/backend/mcp/external/project.ts +1 -1
- package/backend/mcp/internal/remote-server.test.ts +1 -3
- package/backend/mcp/internal/remote-server.ts +4 -4
- package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
- package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
- package/backend/memory/redact.ts +1 -1
- package/backend/notes/access.test.ts +28 -29
- package/backend/notes/access.ts +6 -11
- package/backend/permissions/service.ts +1 -1
- package/backend/preview/browser/browser-clipboard.test.ts +46 -0
- package/backend/preview/browser/browser-clipboard.ts +67 -0
- package/backend/preview/browser/browser-dialog-handler.ts +95 -6
- package/backend/preview/browser/browser-host-bridge.ts +9 -0
- package/backend/preview/browser/browser-interaction-handler.ts +316 -86
- package/backend/preview/browser/browser-mcp-control.ts +34 -0
- package/backend/preview/browser/browser-pool.ts +67 -6
- package/backend/preview/browser/browser-preview-service.ts +361 -25
- package/backend/preview/browser/browser-tab-manager.ts +66 -23
- package/backend/preview/browser/browser-video-capture.ts +92 -5
- package/backend/preview/browser/element-locator.ts +190 -17
- package/backend/preview/browser/keyboard-chords.test.ts +68 -0
- package/backend/preview/browser/keyboard-chords.ts +132 -0
- package/backend/preview/browser/paste.ts +81 -0
- package/backend/preview/browser/process-usage.ts +142 -0
- package/backend/preview/browser/profile-lock.ts +209 -0
- package/backend/preview/browser/scripts/host-bridge.ts +59 -0
- package/backend/preview/browser/scripts/video-stream.ts +58 -0
- package/backend/preview/browser/types.ts +40 -2
- package/backend/preview/browser/viewport.test.ts +45 -0
- package/backend/preview/browser/viewport.ts +96 -0
- package/backend/profiles/service.ts +2 -2
- package/backend/project/status-manager.ts +43 -172
- package/backend/projects/home.ts +61 -0
- package/backend/projects/project-cleanup.integration.test.ts +2 -2
- package/backend/projects/project-cleanup.ts +0 -8
- package/backend/skills/service.ts +2 -3
- package/backend/snapshot/helpers.ts +0 -1
- package/backend/snapshot/restore.ts +252 -0
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +5 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws.ts +61 -154
- package/backend/worktrees/branching/engine.ts +3 -16
- package/backend/worktrees/branching/index.ts +1 -1
- package/backend/worktrees/branching/projector.ts +1 -1
- package/backend/worktrees/branching/service.ts +13 -25
- package/backend/ws/access.ts +12 -21
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/auth/device.ts +16 -71
- package/backend/ws/auth/index.ts +4 -22
- package/backend/ws/auth/login.test.ts +14 -60
- package/backend/ws/auth/login.ts +24 -124
- package/backend/ws/auth/status.ts +0 -1
- package/backend/ws/chat/composer.ts +118 -118
- package/backend/ws/chat/stream.ts +64 -47
- package/backend/ws/chat-apps/index.ts +117 -0
- package/backend/ws/containers/actions.ts +11 -25
- package/backend/ws/containers/index.ts +3 -4
- package/backend/ws/containers/list.ts +10 -36
- package/backend/ws/containers/logs.ts +2 -2
- package/backend/ws/containers/tunnel.ts +1 -2
- package/backend/ws/db-client/access.ts +2 -16
- package/backend/ws/db-client/accounts.ts +5 -15
- package/backend/ws/db-client/connections.ts +17 -25
- package/backend/ws/db-client/context.ts +1 -1
- package/backend/ws/db-client/env.ts +7 -10
- package/backend/ws/db-client/index.ts +2 -2
- package/backend/ws/db-client/io.ts +5 -5
- package/backend/ws/db-client/query-history-retention.test.ts +8 -8
- package/backend/ws/db-client/query.ts +18 -17
- package/backend/ws/db-client/schema.ts +13 -13
- package/backend/ws/db-client/structure.ts +35 -35
- package/backend/ws/db-client/supabase.ts +4 -21
- package/backend/ws/deployments/context.ts +1 -1
- package/backend/ws/deployments/crud.ts +0 -5
- package/backend/ws/engine/access.ts +7 -20
- package/backend/ws/engine/claude/accounts.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +5 -5
- package/backend/ws/engine/codex/accounts.ts +3 -3
- package/backend/ws/engine/pi/accounts.ts +5 -5
- package/backend/ws/files/clipboard.ts +8 -27
- package/backend/ws/files/image-edit.ts +6 -6
- package/backend/ws/files/index.ts +1 -1
- package/backend/ws/files/path-access.test.ts +32 -131
- package/backend/ws/files/path-access.ts +8 -87
- package/backend/ws/files/read.ts +15 -19
- package/backend/ws/files/reveal.ts +3 -3
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/share.ts +9 -13
- package/backend/ws/files/state.ts +9 -12
- package/backend/ws/files/watch.ts +3 -3
- package/backend/ws/files/write.ts +30 -31
- package/backend/ws/git/branch.ts +80 -59
- package/backend/ws/git/commit.ts +63 -44
- package/backend/ws/git/conflict.ts +16 -18
- package/backend/ws/git/identity-context.ts +8 -17
- package/backend/ws/git/identity.ts +17 -27
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/op-state.ts +139 -0
- package/backend/ws/git/remote.ts +241 -141
- package/backend/ws/git/repo-context.ts +67 -0
- package/backend/ws/git/staging.ts +18 -28
- package/backend/ws/git/status.ts +5 -2
- package/backend/ws/index.ts +5 -1
- package/backend/ws/instructions/crud.ts +1 -1
- package/backend/ws/integrations/crud.ts +1 -3
- package/backend/ws/mcp/crud.ts +3 -5
- package/backend/ws/mcp/tools.ts +1 -1
- package/backend/ws/memory/crud.ts +14 -46
- package/backend/ws/memory/index.ts +2 -2
- package/backend/ws/messages/crud.ts +29 -8
- package/backend/ws/notes/index.ts +33 -39
- package/backend/ws/permissions/crud.ts +3 -4
- package/backend/ws/ports/index.ts +1 -2
- package/backend/ws/ports/kill.ts +5 -10
- package/backend/ws/ports/list.ts +4 -10
- package/backend/ws/preview/access.ts +1 -1
- package/backend/ws/preview/browser/interact.ts +52 -79
- package/backend/ws/preview/browser/native-ui.ts +24 -0
- package/backend/ws/preview/browser/stats.ts +98 -1
- package/backend/ws/preview/browser/tab-info.ts +15 -0
- package/backend/ws/preview/browser/tab.ts +19 -4
- package/backend/ws/preview/index.ts +27 -0
- package/backend/ws/profiles/crud.ts +6 -8
- package/backend/ws/project-artifacts/index.ts +30 -31
- package/backend/ws/projects/crud.ts +33 -35
- package/backend/ws/projects/index.ts +3 -8
- package/backend/ws/projects/info.ts +3 -3
- package/backend/ws/projects/overview.ts +19 -30
- package/backend/ws/projects/status.ts +17 -57
- package/backend/ws/sessions/crud.ts +34 -45
- package/backend/ws/sessions/index.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/skills/crud.ts +3 -4
- package/backend/ws/skills/index.ts +1 -1
- package/backend/ws/snapshot/changes.ts +7 -7
- package/backend/ws/snapshot/restore.ts +11 -295
- package/backend/ws/snapshot/timeline.ts +2 -4
- package/backend/ws/ssh/access.ts +6 -21
- package/backend/ws/ssh/connections.ts +21 -31
- package/backend/ws/ssh/forwards.ts +12 -12
- package/backend/ws/ssh/sftp.ts +34 -34
- package/backend/ws/ssh/tunnel.ts +1 -2
- package/backend/ws/stack/install.ts +7 -17
- package/backend/ws/subagents/crud.ts +1 -1
- package/backend/ws/tunnel/share.ts +0 -2
- package/backend/ws/user/crud.ts +1 -59
- package/backend/ws/user/index.ts +1 -1
- package/backend/ws/work/context.ts +1 -1
- package/backend/ws/work/crud.ts +0 -5
- package/backend/ws/workspace/state.ts +10 -13
- package/backend/ws/worktrees/branching.ts +7 -36
- package/backend/ws/worktrees/crud.ts +2 -2
- package/bin/clopen.ts +10 -11
- package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
- package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
- package/dist/assets/main-BUiUL3eZ.css +1 -0
- package/dist/assets/main-nBOb9YOA.js +1240 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/constants/attachments.ts +14 -0
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/preview.test.ts +259 -0
- package/shared/constants/preview.ts +1018 -57
- package/shared/constants/tool-icons.ts +5 -0
- package/shared/types/containers/container.ts +1 -1
- package/shared/types/database/schema.ts +9 -6
- package/shared/types/git-identity.ts +1 -1
- package/shared/types/git.ts +116 -0
- package/shared/types/integrations.ts +7 -0
- package/shared/types/stores/settings.ts +1 -1
- package/shared/types/unified/index.ts +1 -1
- package/shared/types/unified/message.ts +0 -7
- package/shared/types/unified/stream.ts +2 -4
- package/shared/types/unified/tool.ts +15 -1
- package/shared/utils/ask-user-question.test.ts +319 -0
- package/shared/utils/ask-user-question.ts +154 -0
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/ws-server.ts +32 -7
- package/backend/auth/session-invalidation.test.ts +0 -112
- package/backend/auth/session-invalidation.ts +0 -77
- package/backend/project/status-manager.test.ts +0 -32
- package/backend/ws/auth/invites.ts +0 -94
- package/backend/ws/auth/users.ts +0 -112
- package/backend/ws/projects/presence.ts +0 -46
- package/backend/ws/stack/access.ts +0 -31
- package/dist/assets/main-BiDNMWb3.css +0 -1
- package/dist/assets/main-BlhKWz2B.js +0 -1241
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The control catalog — the single source of truth for what Clopen can be
|
|
3
|
+
* told to do from outside its web UI.
|
|
4
|
+
*
|
|
5
|
+
* types.ts the action / context / result contract
|
|
6
|
+
* define.ts `defineAction()`, validated at import
|
|
7
|
+
* invoke.ts running a WebSocket route as a user (the web UI's own rules)
|
|
8
|
+
* workspace.ts shared answers: model for a new session, latest session, …
|
|
9
|
+
* links.ts links back into the web UI
|
|
10
|
+
* actions/ the actions, one file per area
|
|
11
|
+
*
|
|
12
|
+
* Every remote surface is generated from `CONTROL_ACTIONS`: a chat app's
|
|
13
|
+
* commands, `/` menu, buttons and help today; an MCP server's tool schema
|
|
14
|
+
* (`describeControlActions()`) when one is built. Adding a capability to
|
|
15
|
+
* remote control is adding an action here — never a handler in a surface.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { Value } from '@sinclair/typebox/value';
|
|
19
|
+
import type { AuthUser } from '$backend/auth/auth-service';
|
|
20
|
+
import { callRouteAs } from './invoke';
|
|
21
|
+
import { CONTROL_GROUP_LABELS, type ControlAction, type ControlContext, type ControlGroup, type ControlResult, type ControlTarget } from './types';
|
|
22
|
+
import { browseFolders, createProject, deleteFolder, goHome, listProjects, makeFolder, openProject, renameFolder } from './actions/projects';
|
|
23
|
+
import { deleteSession, dropQueued, listSessions, newSession, openSession, runningSessions, searchSessions, sessionStatus, showQueue, stopSession } from './actions/sessions';
|
|
24
|
+
import { listSkills, runSkill } from './actions/skills';
|
|
25
|
+
import { getFile, turnDiff } from './actions/files';
|
|
26
|
+
import { listEngines, listModels, listReasoning, setModel, setReasoning } from './actions/models';
|
|
27
|
+
import { listAccounts, switchAccount } from './actions/accounts';
|
|
28
|
+
|
|
29
|
+
export type { ControlAction, ControlChoice, ControlContext, ControlFile, ControlGroup, ControlResult, ControlTarget, ControlCommand } from './types';
|
|
30
|
+
export { CONTROL_GROUP_LABELS } from './types';
|
|
31
|
+
export { matchSkill, normaliseSkillName } from './actions/skills';
|
|
32
|
+
export { registerControlRouter, callRouteAs } from './invoke';
|
|
33
|
+
export { setPublicOriginResolver, sessionLink, publicOrigin } from './links';
|
|
34
|
+
export * from './workspace';
|
|
35
|
+
|
|
36
|
+
/** Every action, in the order help and every command menu list them. */
|
|
37
|
+
export const CONTROL_ACTIONS: readonly ControlAction[] = [
|
|
38
|
+
sessionStatus,
|
|
39
|
+
runningSessions,
|
|
40
|
+
newSession,
|
|
41
|
+
listSessions,
|
|
42
|
+
searchSessions,
|
|
43
|
+
openSession,
|
|
44
|
+
stopSession,
|
|
45
|
+
showQueue,
|
|
46
|
+
dropQueued,
|
|
47
|
+
deleteSession,
|
|
48
|
+
turnDiff,
|
|
49
|
+
getFile,
|
|
50
|
+
listSkills,
|
|
51
|
+
runSkill,
|
|
52
|
+
listProjects,
|
|
53
|
+
openProject,
|
|
54
|
+
goHome,
|
|
55
|
+
browseFolders,
|
|
56
|
+
makeFolder,
|
|
57
|
+
renameFolder,
|
|
58
|
+
deleteFolder,
|
|
59
|
+
createProject,
|
|
60
|
+
listEngines,
|
|
61
|
+
listModels,
|
|
62
|
+
setModel,
|
|
63
|
+
listReasoning,
|
|
64
|
+
setReasoning,
|
|
65
|
+
listAccounts,
|
|
66
|
+
switchAccount
|
|
67
|
+
] as unknown as ControlAction[];
|
|
68
|
+
|
|
69
|
+
const byId = new Map(CONTROL_ACTIONS.map((action) => [action.id, action]));
|
|
70
|
+
const byCommand = new Map<string, ControlAction>();
|
|
71
|
+
for (const action of CONTROL_ACTIONS) {
|
|
72
|
+
const name = action.command?.name;
|
|
73
|
+
if (!name) continue;
|
|
74
|
+
if (byCommand.has(name)) throw new Error(`Control command /${name} is declared twice`);
|
|
75
|
+
byCommand.set(name, action);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function getControlAction(id: string): ControlAction | null {
|
|
79
|
+
return byId.get(id) ?? null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function controlActionForCommand(name: string): ControlAction | null {
|
|
83
|
+
return byCommand.get(name) ?? null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The command-bearing actions, in catalog order. */
|
|
87
|
+
function commandActions(): ControlAction[] {
|
|
88
|
+
return CONTROL_ACTIONS.filter((action) => action.command);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Free text after a command → the action's arguments. One key takes the whole
|
|
93
|
+
* text; several keys take one word each, the last taking the rest.
|
|
94
|
+
*/
|
|
95
|
+
export function parseCommandArgument(action: ControlAction, text: string): Record<string, unknown> {
|
|
96
|
+
const keys = action.command?.argument?.keys ?? [];
|
|
97
|
+
const trimmed = text.trim();
|
|
98
|
+
if (keys.length === 0 || !trimmed) return {};
|
|
99
|
+
if (keys.length === 1) return { [keys[0]]: trimmed };
|
|
100
|
+
const out: Record<string, unknown> = {};
|
|
101
|
+
let rest = trimmed;
|
|
102
|
+
for (const [index, key] of keys.entries()) {
|
|
103
|
+
if (!rest) break;
|
|
104
|
+
if (index === keys.length - 1) {
|
|
105
|
+
out[key] = rest;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
const match = /^(\S+)\s*([\s\S]*)$/.exec(rest);
|
|
109
|
+
if (!match) break;
|
|
110
|
+
out[key] = match[1];
|
|
111
|
+
rest = match[2];
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function createControlContext(user: AuthUser, target: ControlTarget): ControlContext {
|
|
117
|
+
return {
|
|
118
|
+
user,
|
|
119
|
+
target,
|
|
120
|
+
call: (action, data, options) => callRouteAs(user, action, data ?? {}, options?.projectId ?? target.projectId)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Validate arguments against the action's schema; a readable error when they do not fit. */
|
|
125
|
+
export function checkArgs(action: ControlAction, args: Record<string, unknown>): Record<string, unknown> {
|
|
126
|
+
try {
|
|
127
|
+
return Value.Decode(action.args, Value.Convert(action.args, args)) as Record<string, unknown>;
|
|
128
|
+
} catch {
|
|
129
|
+
const hint = action.command?.argument ? ` Usage: /${action.command.name} ${action.command.argument.hint}` : '';
|
|
130
|
+
throw new Error(`That is not quite right for ${action.title}.${hint}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The confirmation question an action wants asked first, if any. */
|
|
135
|
+
export async function confirmationFor(action: ControlAction, ctx: ControlContext, args: Record<string, unknown>): Promise<string | null> {
|
|
136
|
+
return action.confirm ? await action.confirm(args as never, ctx) : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Run an action as `ctx.user`: validated arguments, then the action. */
|
|
140
|
+
export async function runControlAction(ctx: ControlContext, actionId: string, rawArgs: Record<string, unknown>): Promise<ControlResult> {
|
|
141
|
+
const action = getControlAction(actionId);
|
|
142
|
+
if (!action) throw new Error('That is no longer available.');
|
|
143
|
+
const args = checkArgs(action, rawArgs);
|
|
144
|
+
return action.run(ctx, args as never);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** One line of a command reference — what help, a `/` menu and Settings all list. */
|
|
148
|
+
export interface CommandEntry {
|
|
149
|
+
command: string;
|
|
150
|
+
hint: string | null;
|
|
151
|
+
description: string;
|
|
152
|
+
group: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Every command that can be typed, in one order: a surface's own commands
|
|
157
|
+
* (`extra`) first, then the catalog's, grouped. Help, the command menu a
|
|
158
|
+
* chat app publishes and the reference in Settings are all THIS list, so
|
|
159
|
+
* they can never disagree about what exists.
|
|
160
|
+
*/
|
|
161
|
+
export function commandReference(
|
|
162
|
+
extra: Array<{ command: string; description: string; hint?: string | null }> = []
|
|
163
|
+
): CommandEntry[] {
|
|
164
|
+
const own = extra.map((entry) => ({
|
|
165
|
+
command: entry.command,
|
|
166
|
+
hint: entry.hint ?? null,
|
|
167
|
+
description: entry.description,
|
|
168
|
+
group: CONTROL_GROUP_LABELS.conversation
|
|
169
|
+
}));
|
|
170
|
+
const byGroup = new Map<ControlGroup, ControlAction[]>();
|
|
171
|
+
for (const action of commandActions()) {
|
|
172
|
+
const list = byGroup.get(action.group) ?? [];
|
|
173
|
+
list.push(action);
|
|
174
|
+
byGroup.set(action.group, list);
|
|
175
|
+
}
|
|
176
|
+
const catalog = [...byGroup.entries()].flatMap(([group, actions]) =>
|
|
177
|
+
actions.map((action) => ({
|
|
178
|
+
command: action.command!.name,
|
|
179
|
+
hint: action.command!.argument?.hint ?? null,
|
|
180
|
+
description: action.description,
|
|
181
|
+
group: CONTROL_GROUP_LABELS[group]
|
|
182
|
+
}))
|
|
183
|
+
);
|
|
184
|
+
return [...own, ...catalog];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Help as Markdown, grouped — `commandReference()` written out. */
|
|
188
|
+
export function controlHelp(extra: Array<{ command: string; description: string; hint?: string | null }> = []): string {
|
|
189
|
+
const lines: string[] = [];
|
|
190
|
+
let group: string | null = null;
|
|
191
|
+
for (const entry of commandReference(extra)) {
|
|
192
|
+
if (entry.group !== group) {
|
|
193
|
+
if (group !== null) lines.push('');
|
|
194
|
+
lines.push(`**${entry.group}**`);
|
|
195
|
+
group = entry.group;
|
|
196
|
+
}
|
|
197
|
+
lines.push(`/${entry.command}${entry.hint ? ` ${entry.hint}` : ''}: ${entry.description}`);
|
|
198
|
+
}
|
|
199
|
+
return lines.join('\n');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The catalog as data — what an MCP server will publish as its tool schema. */
|
|
203
|
+
export function describeControlActions() {
|
|
204
|
+
return CONTROL_ACTIONS.map((action) => ({
|
|
205
|
+
id: action.id,
|
|
206
|
+
group: action.group,
|
|
207
|
+
title: action.title,
|
|
208
|
+
description: action.description,
|
|
209
|
+
destructive: Boolean(action.confirm),
|
|
210
|
+
command: action.command?.name ?? null,
|
|
211
|
+
args: action.args
|
|
212
|
+
}));
|
|
213
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Running a WebSocket route as a user, without a browser.
|
|
3
|
+
*
|
|
4
|
+
* The WebSocket API is already the complete, permission-checked, schema-typed
|
|
5
|
+
* description of everything Clopen can do; a second implementation for remote
|
|
6
|
+
* control would drift from it on day one. So an action calls the route itself,
|
|
7
|
+
* through a virtual connection carrying the user's identity: the router's auth
|
|
8
|
+
* gate (`auth/permissions.ts`), request validation and handler run exactly as
|
|
9
|
+
* they do for a tab, and the handler's return value comes back here instead of
|
|
10
|
+
* down a socket.
|
|
11
|
+
*
|
|
12
|
+
* The router is handed over at startup rather than imported: `backend/ws`
|
|
13
|
+
* imports the chat-app routes, which import this — importing it back would be
|
|
14
|
+
* a cycle.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { WSRouter } from '$shared/utils/ws-server';
|
|
18
|
+
import { ws } from '$backend/utils/ws';
|
|
19
|
+
import type { AuthUser } from '$backend/auth/auth-service';
|
|
20
|
+
|
|
21
|
+
let router: Pick<WSRouter, 'invoke'> | null = null;
|
|
22
|
+
|
|
23
|
+
export function registerControlRouter(instance: Pick<WSRouter, 'invoke'>): void {
|
|
24
|
+
router = instance;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function requireRouter(): Pick<WSRouter, 'invoke'> {
|
|
28
|
+
if (!router) throw new Error('The control surface is not ready yet');
|
|
29
|
+
return router;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function callRouteAs<T = unknown>(
|
|
33
|
+
user: Pick<AuthUser, 'id'>,
|
|
34
|
+
action: string,
|
|
35
|
+
data: Record<string, unknown> = {},
|
|
36
|
+
projectId: string | null = null
|
|
37
|
+
): Promise<T> {
|
|
38
|
+
const conn = ws.openVirtualConnection({ userId: user.id, projectId });
|
|
39
|
+
try {
|
|
40
|
+
return (await requireRouter().invoke(conn, action, data)) as T;
|
|
41
|
+
} finally {
|
|
42
|
+
ws.closeVirtualConnection(conn);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Links back into the web UI.
|
|
3
|
+
*
|
|
4
|
+
* Only an address another device can open is worth sending. The default looks
|
|
5
|
+
* for one without side effects (configured URL or a running tunnel); a surface
|
|
6
|
+
* that knows better — the chat-app runtime remembers the last real domain a
|
|
7
|
+
* browser used — registers its own resolver.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { findPublicOrigin, isLocalHostname } from '$backend/tunnel/public-origin';
|
|
11
|
+
|
|
12
|
+
let resolver: () => string | null = () => {
|
|
13
|
+
const found = findPublicOrigin();
|
|
14
|
+
if (!found) return null;
|
|
15
|
+
try {
|
|
16
|
+
const url = new URL(found.origin);
|
|
17
|
+
return url.protocol === 'https:' && !isLocalHostname(url.hostname) ? found.origin : null;
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function setPublicOriginResolver(next: () => string | null): void {
|
|
24
|
+
resolver = next;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function publicOrigin(): string | null {
|
|
28
|
+
return resolver();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The `#session/<project>/<session>` deep link, or null when nothing outside can open it. */
|
|
32
|
+
export function sessionLink(projectId: string, sessionId: string): string | null {
|
|
33
|
+
const origin = publicOrigin();
|
|
34
|
+
return origin ? `${origin}/#session/${encodeURIComponent(projectId)}/${encodeURIComponent(sessionId)}` : null;
|
|
35
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paging for lists a person picks from. A chat screen holds a dozen items and
|
|
3
|
+
* a keyboard holds a few dozen buttons, so every list is cut into pages with
|
|
4
|
+
* a "More…" choice that asks the same action for the next one.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { ControlChoice } from './types';
|
|
8
|
+
|
|
9
|
+
export const PAGE_SIZE = 20;
|
|
10
|
+
|
|
11
|
+
export function paged<T>(
|
|
12
|
+
items: T[],
|
|
13
|
+
page: number | undefined,
|
|
14
|
+
toChoice: (item: T) => ControlChoice,
|
|
15
|
+
more: { action: string; args?: Record<string, unknown> },
|
|
16
|
+
size = PAGE_SIZE
|
|
17
|
+
): { choices: ControlChoice[]; range: string } {
|
|
18
|
+
const index = Math.max(0, page ?? 0);
|
|
19
|
+
const slice = items.slice(index * size, (index + 1) * size);
|
|
20
|
+
const choices = slice.map(toChoice);
|
|
21
|
+
if ((index + 1) * size < items.length) {
|
|
22
|
+
choices.push({ label: 'More…', action: more.action, args: { ...(more.args ?? {}), page: index + 1 } });
|
|
23
|
+
}
|
|
24
|
+
const range = items.length > size ? ` (${index * size + 1}–${index * size + slice.length} of ${items.length})` : '';
|
|
25
|
+
return { choices, range };
|
|
26
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The control catalog's contract.
|
|
3
|
+
*
|
|
4
|
+
* An ACTION is one thing a user can make Clopen do from outside the web UI —
|
|
5
|
+
* open a project, switch a model, run a skill. It is declared once,
|
|
6
|
+
* here, and every remote surface is generated from it: a chat app's commands,
|
|
7
|
+
* buttons and help today, an MCP server's tool schema tomorrow. A surface
|
|
8
|
+
* never implements an operation; it renders an action's result.
|
|
9
|
+
*
|
|
10
|
+
* Actions are deliberately surface-neutral. They take explicit arguments
|
|
11
|
+
* (validated against a TypeBox schema, which is also what an MCP client will
|
|
12
|
+
* be shown), act as one user against one target, and return a result made of
|
|
13
|
+
* Markdown, follow-up choices and an optional new target — things a chat
|
|
14
|
+
* renders as text and buttons and an agent reads as data.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { Static, TSchema } from 'elysia';
|
|
18
|
+
import type { AuthUser } from '$backend/auth/auth-service';
|
|
19
|
+
|
|
20
|
+
/** Where an action acts: a project (Home when none was picked) and maybe a session. */
|
|
21
|
+
export interface ControlTarget {
|
|
22
|
+
projectId: string;
|
|
23
|
+
sessionId: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ControlContext {
|
|
27
|
+
user: AuthUser;
|
|
28
|
+
target: ControlTarget;
|
|
29
|
+
/**
|
|
30
|
+
* Run a WebSocket route as this user — the SAME route, auth gate and
|
|
31
|
+
* validation the web UI goes through. The project defaults to the target's.
|
|
32
|
+
*/
|
|
33
|
+
call<T = unknown>(action: string, data?: Record<string, unknown>, options?: { projectId?: string }): Promise<T>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A follow-up the user can pick: a button in a chat, an option for an agent. */
|
|
37
|
+
export interface ControlChoice {
|
|
38
|
+
label: string;
|
|
39
|
+
/** A second line of context — a path, a provider, a state. */
|
|
40
|
+
detail?: string;
|
|
41
|
+
current?: boolean;
|
|
42
|
+
action: string;
|
|
43
|
+
args?: Record<string, unknown>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A file an action hands back — sent as a file in a chat, a path to an agent. */
|
|
47
|
+
export interface ControlFile {
|
|
48
|
+
/** Absolute path on the Clopen machine. */
|
|
49
|
+
path: string;
|
|
50
|
+
filename: string;
|
|
51
|
+
mime: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ControlResult {
|
|
55
|
+
/** Markdown. */
|
|
56
|
+
text: string;
|
|
57
|
+
/** Files to deliver with the text. */
|
|
58
|
+
files?: ControlFile[];
|
|
59
|
+
/**
|
|
60
|
+
* A message to send to the target session as the user, after the text: an
|
|
61
|
+
* action that STARTS a turn (running a skill) says what to send, and the
|
|
62
|
+
* surface sends it the way it sends anything the user types.
|
|
63
|
+
*/
|
|
64
|
+
prompt?: string;
|
|
65
|
+
/**
|
|
66
|
+
* The action needs words from the user (a folder name): what to ask, and
|
|
67
|
+
* which action gets them, as argument `key` next to `args`. A chat takes
|
|
68
|
+
* the next message (or a reply) as the answer; an agent passes it directly.
|
|
69
|
+
*/
|
|
70
|
+
ask?: { question: string; action: string; args?: Record<string, unknown>; key: string };
|
|
71
|
+
choices?: ControlChoice[];
|
|
72
|
+
/** Where the conversation is after this action, when it moved. */
|
|
73
|
+
target?: ControlTarget;
|
|
74
|
+
/** A link worth opening — rendered as a button in a chat. */
|
|
75
|
+
link?: { label: string; url: string };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type ControlGroup = 'conversation' | 'sessions' | 'files' | 'skills' | 'projects' | 'models' | 'accounts';
|
|
79
|
+
|
|
80
|
+
export const CONTROL_GROUP_LABELS: Record<ControlGroup, string> = {
|
|
81
|
+
conversation: 'Conversation',
|
|
82
|
+
sessions: 'Sessions',
|
|
83
|
+
files: 'Files',
|
|
84
|
+
skills: 'Skills',
|
|
85
|
+
projects: 'Projects',
|
|
86
|
+
models: 'Models',
|
|
87
|
+
accounts: 'Engine accounts'
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
export interface ControlCommand {
|
|
91
|
+
/**
|
|
92
|
+
* `[a-z0-9_]`, 1-32 characters — the strictest platform's rule (Telegram).
|
|
93
|
+
* One name per action, no aliases: a surface lists every command it
|
|
94
|
+
* accepts, so a hidden second name would be a command nobody can find.
|
|
95
|
+
*/
|
|
96
|
+
name: string;
|
|
97
|
+
/**
|
|
98
|
+
* What free text after the command fills. A single key receives the whole
|
|
99
|
+
* text; `split` keys receive whitespace-separated words, the last one
|
|
100
|
+
* taking the rest.
|
|
101
|
+
*/
|
|
102
|
+
argument?: { keys: string[]; hint: string };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ControlAction<A extends TSchema = TSchema> {
|
|
106
|
+
/** `group.verb` — stable, used in button data and by future MCP clients. */
|
|
107
|
+
id: string;
|
|
108
|
+
group: ControlGroup;
|
|
109
|
+
title: string;
|
|
110
|
+
/** One line, shown in help and to an agent. */
|
|
111
|
+
description: string;
|
|
112
|
+
args: A;
|
|
113
|
+
command?: ControlCommand;
|
|
114
|
+
/** A question to ask before running, for anything destructive. Null: just run it. */
|
|
115
|
+
confirm?: (args: Static<A>, ctx: ControlContext) => string | null | Promise<string | null>;
|
|
116
|
+
run(ctx: ControlContext, args: Static<A>): Promise<ControlResult>;
|
|
117
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared facts about a user's workspace that more than one remote surface
|
|
3
|
+
* needs: which model a new session should use, how a project is named, what
|
|
4
|
+
* the latest session is. Kept here so the chat app's conversation and the
|
|
5
|
+
* control actions answer these questions the same way.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { EngineType } from '$shared/types/unified';
|
|
9
|
+
import type { ChatSession, Project } from '$shared/types/database/schema';
|
|
10
|
+
import { engineQueries, projectQueries, sessionQueries, settingsQueries } from '$backend/database/queries';
|
|
11
|
+
import { streamManager } from '$backend/chat/stream-manager';
|
|
12
|
+
import { ensureHomeProject } from '$backend/projects/home';
|
|
13
|
+
import { ws } from '$backend/utils/ws';
|
|
14
|
+
import { isHomeProject, HOME_PROJECT_NAME } from '$shared/utils/home-project';
|
|
15
|
+
import { debug } from '$shared/utils/logger';
|
|
16
|
+
import type { ControlTarget } from './types';
|
|
17
|
+
|
|
18
|
+
export interface ModelChoice {
|
|
19
|
+
engine: EngineType;
|
|
20
|
+
provider: string;
|
|
21
|
+
modelId: string;
|
|
22
|
+
modelName: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function modelOf(session: ChatSession | null | undefined): ModelChoice | null {
|
|
26
|
+
if (!session?.engine || !session.model_id) return null;
|
|
27
|
+
return { engine: session.engine, provider: session.provider ?? '', modelId: session.model_id, modelName: session.model_name ?? session.model_id };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The model last picked in Clopen — the saved settings blob, read here only for this. */
|
|
31
|
+
export function settingsModel(userId: string): ModelChoice | null {
|
|
32
|
+
try {
|
|
33
|
+
const raw = settingsQueries.get(`user:${userId}:settings`)?.value;
|
|
34
|
+
const settings = raw ? JSON.parse(raw) : null;
|
|
35
|
+
if (settings?.selectedEngine && settings?.selectedModelId) {
|
|
36
|
+
return {
|
|
37
|
+
engine: settings.selectedEngine,
|
|
38
|
+
provider: settings.selectedProvider ?? '',
|
|
39
|
+
modelId: settings.selectedModelId,
|
|
40
|
+
modelName: settings.selectedModelName ?? settings.selectedModelId
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
} catch {
|
|
44
|
+
// Unreadable settings: fall through to the user's sessions.
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function byRecency(a: ChatSession, b: ChatSession): number {
|
|
50
|
+
return (b.last_message_at ?? b.started_at).localeCompare(a.last_message_at ?? a.started_at);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function recentSessions(projectId?: string): ChatSession[] {
|
|
54
|
+
const projects = projectId ? [projectId] : projectQueries.getListed().map((project) => project.id);
|
|
55
|
+
return projects.flatMap((id) => sessionQueries.getByProjectId(id)).sort(byRecency);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A model for a NEW session: this project's latest, the user's picked one, then any they used. */
|
|
59
|
+
export function pickModel(userId: string, projectId: string): ModelChoice | null {
|
|
60
|
+
const inProject = recentSessions(projectId).map(modelOf).find(Boolean);
|
|
61
|
+
return inProject ?? settingsModel(userId) ?? recentSessions().map(modelOf).find(Boolean) ?? null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The engine account a turn signs in with — what the web picker would send.
|
|
66
|
+
* The session's own account when it pinned one of THIS engine's; otherwise
|
|
67
|
+
* the active account of the model's provider, else of the engine. Null when
|
|
68
|
+
* the engine has none (the stream then says so, and why).
|
|
69
|
+
*/
|
|
70
|
+
export function accountFor(session: ChatSession, model: ModelChoice): { id: number; name: string } | null {
|
|
71
|
+
if (session.account_id) {
|
|
72
|
+
const pinned = engineQueries.getAccount(session.account_id);
|
|
73
|
+
const provider = pinned ? engineQueries.getProvider(pinned.provider_id) : null;
|
|
74
|
+
if (pinned && provider?.engine_type === model.engine) return { id: pinned.id, name: pinned.name };
|
|
75
|
+
}
|
|
76
|
+
const provider = model.provider ? engineQueries.getProviderBySlug(model.engine, model.provider) : null;
|
|
77
|
+
const active = (provider ? engineQueries.getActiveAccount(provider.id) : null) ?? engineQueries.getActiveAccountForEngine(model.engine);
|
|
78
|
+
return active ? { id: active.id, name: active.name } : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function latestSession(projectId: string): ChatSession | null {
|
|
82
|
+
return sessionQueries.getByProjectId(projectId).sort(byRecency)[0] ?? null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function projectLabel(project: Project): string {
|
|
86
|
+
return isHomeProject(project) ? HOME_PROJECT_NAME : project.name;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function isSessionBusy(session: ChatSession): boolean {
|
|
90
|
+
return streamManager.getSessionStream(session.id, session.project_id)?.status === 'active';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A new, empty session in `project`, using `model`, announced to any open tab. */
|
|
94
|
+
export function createSession(project: Project, model: ModelChoice): ChatSession {
|
|
95
|
+
const session = sessionQueries.create({
|
|
96
|
+
project_id: project.id,
|
|
97
|
+
engine: model.engine,
|
|
98
|
+
started_at: new Date().toISOString()
|
|
99
|
+
});
|
|
100
|
+
sessionQueries.updateEngineModel(session.id, model.engine, model.provider, model.modelId, model.modelName);
|
|
101
|
+
const created = sessionQueries.getById(session.id) ?? session;
|
|
102
|
+
try {
|
|
103
|
+
ws.emit.project(project.id, 'sessions:session-available', { session: created });
|
|
104
|
+
} catch (error) {
|
|
105
|
+
debug.warn('control', 'Announcing a new session failed:', error);
|
|
106
|
+
}
|
|
107
|
+
return created;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Resolve a target to rows that can be acted on. A project that was removed
|
|
112
|
+
* falls back to Home; a session outside the project is dropped.
|
|
113
|
+
*/
|
|
114
|
+
export function resolveTarget(target: Partial<ControlTarget> | null): { project: Project; session: ChatSession | null } {
|
|
115
|
+
let project = target?.projectId ? projectQueries.getById(target.projectId) : null;
|
|
116
|
+
if (!project || !projectQueries.isListed(project.id)) project = ensureHomeProject();
|
|
117
|
+
const session = target?.sessionId ? sessionQueries.getById(target.sessionId) : null;
|
|
118
|
+
return { project, session: session && session.project_id === project.id ? session : null };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A session that can be acted on, with its project. */
|
|
122
|
+
export function accessibleSession(sessionId: string | null | undefined): { project: Project; session: ChatSession } | null {
|
|
123
|
+
const session = sessionId ? sessionQueries.getById(sessionId) : null;
|
|
124
|
+
const project = session ? projectQueries.getById(session.project_id) : null;
|
|
125
|
+
if (!session || !project || !projectQueries.isListed(project.id)) return null;
|
|
126
|
+
return { project, session };
|
|
127
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
|
|
3
|
+
import { debug } from '$shared/utils/logger';
|
|
4
|
+
|
|
5
|
+
export const description = 'Create chat-app channel links and channel messages';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Two tables, and neither holds a credential — the bot token lives on the
|
|
9
|
+
* `integration_accounts` row a link points at, sealed there.
|
|
10
|
+
*
|
|
11
|
+
* `channel_links` is one CHAT paired with one Clopen USER through one
|
|
12
|
+
* connected bot. A member's chat starts `pending` until an admin approves it;
|
|
13
|
+
* `is_enabled` turns a chat off entirely (it can then do nothing at all). It
|
|
14
|
+
* also carries the chat's ACTIVE TARGET: the project and session a plain
|
|
15
|
+
* message continues.
|
|
16
|
+
*
|
|
17
|
+
* `channel_messages` maps chat messages to Clopen in both directions: a
|
|
18
|
+
* question waiting for an answer, a menu or a confirmation whose buttons
|
|
19
|
+
* name its row, an answer or a user message a reply or an edit can act on.
|
|
20
|
+
*/
|
|
21
|
+
export const up = (db: DatabaseConnection): void => {
|
|
22
|
+
debug.log('migration', '📋 Creating channel tables...');
|
|
23
|
+
|
|
24
|
+
db.exec(`
|
|
25
|
+
CREATE TABLE channel_links (
|
|
26
|
+
id TEXT PRIMARY KEY,
|
|
27
|
+
account_id TEXT NOT NULL REFERENCES integration_accounts(id) ON DELETE CASCADE,
|
|
28
|
+
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
29
|
+
conversation_id TEXT NOT NULL,
|
|
30
|
+
platform_user_id TEXT NOT NULL,
|
|
31
|
+
display_name TEXT,
|
|
32
|
+
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved')),
|
|
33
|
+
is_enabled INTEGER NOT NULL DEFAULT 1,
|
|
34
|
+
active_project_id TEXT,
|
|
35
|
+
active_session_id TEXT,
|
|
36
|
+
created_at TEXT NOT NULL,
|
|
37
|
+
last_used_at TEXT,
|
|
38
|
+
UNIQUE (account_id, conversation_id)
|
|
39
|
+
)
|
|
40
|
+
`);
|
|
41
|
+
db.exec('CREATE INDEX idx_channel_links_user ON channel_links (user_id)');
|
|
42
|
+
|
|
43
|
+
db.exec(`
|
|
44
|
+
CREATE TABLE channel_messages (
|
|
45
|
+
id TEXT PRIMARY KEY,
|
|
46
|
+
link_id TEXT NOT NULL REFERENCES channel_links(id) ON DELETE CASCADE,
|
|
47
|
+
kind TEXT NOT NULL CHECK (kind IN ('question', 'answer', 'user', 'menu', 'confirm')),
|
|
48
|
+
project_id TEXT,
|
|
49
|
+
chat_session_id TEXT,
|
|
50
|
+
tool_use_id TEXT,
|
|
51
|
+
question_index INTEGER,
|
|
52
|
+
clopen_message_id TEXT,
|
|
53
|
+
platform_message_id TEXT NOT NULL,
|
|
54
|
+
state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'answered', 'closed')),
|
|
55
|
+
payload TEXT NOT NULL DEFAULT '{}',
|
|
56
|
+
created_at TEXT NOT NULL
|
|
57
|
+
)
|
|
58
|
+
`);
|
|
59
|
+
db.exec('CREATE INDEX idx_channel_messages_message ON channel_messages (link_id, platform_message_id)');
|
|
60
|
+
db.exec('CREATE INDEX idx_channel_messages_tool_use ON channel_messages (tool_use_id)');
|
|
61
|
+
db.exec('CREATE INDEX idx_channel_messages_session ON channel_messages (chat_session_id, state)');
|
|
62
|
+
|
|
63
|
+
debug.log('migration', '✅ Channel tables created');
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export const down = (db: DatabaseConnection): void => {
|
|
67
|
+
debug.log('migration', '🗑️ Dropping channel tables...');
|
|
68
|
+
db.exec('DROP TABLE IF EXISTS channel_messages');
|
|
69
|
+
db.exec('DROP TABLE IF EXISTS channel_links');
|
|
70
|
+
debug.log('migration', '✅ Channel tables dropped');
|
|
71
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
|
|
3
|
+
import { debug } from '$shared/utils/logger';
|
|
4
|
+
|
|
5
|
+
export const description = 'Add project kind and owner for per-user Home workspaces';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Home is a project row so that everything that needs a project keeps working
|
|
9
|
+
* for a chat with none selected; `kind` tells it apart and `owner_user_id`
|
|
10
|
+
* says whose it is. The partial unique index is the rule "one Home per user",
|
|
11
|
+
* enforced where a race between two tabs cannot get around it.
|
|
12
|
+
*
|
|
13
|
+
* `owner_user_id` deliberately carries NO foreign key: SQLite cannot drop a
|
|
14
|
+
* column that takes part in one, so `down()` would need a rebuild of
|
|
15
|
+
* `projects` — the table half the schema points at. A removed user's Home
|
|
16
|
+
* loses its `user_projects` row with them and is reachable by no one; it is
|
|
17
|
+
* kept, like any project whose last member left, rather than deleted with
|
|
18
|
+
* its sessions behind the admin's back.
|
|
19
|
+
*/
|
|
20
|
+
export const up = (db: DatabaseConnection): void => {
|
|
21
|
+
debug.log('migration', '📋 Adding project kind and owner...');
|
|
22
|
+
db.exec(`ALTER TABLE projects ADD COLUMN kind TEXT NOT NULL DEFAULT 'project' CHECK (kind IN ('project', 'home'))`);
|
|
23
|
+
db.exec(`ALTER TABLE projects ADD COLUMN owner_user_id TEXT`);
|
|
24
|
+
db.exec(`CREATE UNIQUE INDEX idx_projects_home_owner ON projects (owner_user_id) WHERE kind = 'home'`);
|
|
25
|
+
debug.log('migration', '✅ Project kind and owner added');
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const down = (db: DatabaseConnection): void => {
|
|
29
|
+
debug.log('migration', '🗑️ Removing project kind and owner...');
|
|
30
|
+
db.exec('DROP INDEX IF EXISTS idx_projects_home_owner');
|
|
31
|
+
// Home rows have no meaning without the column that marks them.
|
|
32
|
+
db.exec(`DELETE FROM projects WHERE kind = 'home'`);
|
|
33
|
+
db.exec('ALTER TABLE projects DROP COLUMN owner_user_id');
|
|
34
|
+
db.exec('ALTER TABLE projects DROP COLUMN kind');
|
|
35
|
+
debug.log('migration', '✅ Project kind and owner removed');
|
|
36
|
+
};
|