@pixelbyte-software/pixcode 1.54.10 → 1.54.11
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/CODE_OF_CONDUCT.md +41 -41
- package/CONTRIBUTING.md +156 -156
- package/LICENSE +21 -718
- package/README.de.md +169 -169
- package/README.ja.md +167 -167
- package/README.ko.md +167 -167
- package/README.md +435 -418
- package/README.ru.md +169 -169
- package/README.tr.md +298 -298
- package/README.zh-CN.md +167 -167
- package/SECURITY.md +46 -46
- package/dist/api-automation.html +110 -110
- package/dist/api-docs.html +548 -548
- package/dist/assets/{index-DWOW_Jn0.js → index-Bcqs_1vc.js} +114 -114
- package/dist/clear-cache.html +85 -85
- package/dist/convert-icons.md +52 -52
- package/dist/docs.html +308 -308
- package/dist/features.html +133 -133
- package/dist/generate-icons.js +48 -48
- package/dist/humans.txt +15 -15
- package/dist/icons/codex-white.svg +3 -3
- package/dist/icons/codex.svg +3 -3
- package/dist/icons/cursor-white.svg +11 -11
- package/dist/icons/qwen-logo.svg +14 -14
- package/dist/index.html +58 -58
- package/dist/landing.html +268 -268
- package/dist/llms-full.txt +119 -119
- package/dist/llms.txt +53 -53
- package/dist/manifest.json +60 -60
- package/dist/openapi.yaml +1696 -1696
- package/dist/orchestration.html +125 -125
- package/dist/robots.txt +4 -4
- package/dist/site.css +692 -692
- package/dist/sitemap.xml +51 -51
- package/dist/sw.js +132 -132
- package/dist-server/server/cli.js +100 -100
- package/dist-server/server/daemon/manager.js +33 -33
- package/dist-server/server/daemon-manager.js +64 -64
- package/dist-server/server/routes/commands.js +25 -25
- package/dist-server/server/routes/git.js +17 -17
- package/dist-server/server/routes/live-view.js +46 -46
- package/dist-server/server/services/public-api-manifest.js +51 -51
- package/package.json +224 -224
- package/scripts/fix-node-pty.js +67 -67
- package/scripts/github/create-v1.38-issues.mjs +351 -351
- package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
- package/scripts/smoke/backend-resource-bounds.mjs +152 -152
- package/scripts/smoke/changes-panel-layout.mjs +48 -48
- package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
- package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
- package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
- package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
- package/scripts/smoke/chat-session-state.mjs +19 -19
- package/scripts/smoke/code-editor-theme.mjs +55 -55
- package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
- package/scripts/smoke/command-center-agent-writes.mjs +79 -79
- package/scripts/smoke/command-center-non-git.mjs +46 -46
- package/scripts/smoke/context-packet.mjs +43 -43
- package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
- package/scripts/smoke/daemon-entrypoint.mjs +20 -20
- package/scripts/smoke/default-landing-routing.mjs +33 -33
- package/scripts/smoke/desktop-native-notifications.mjs +30 -30
- package/scripts/smoke/desktop-tray-icon.mjs +33 -33
- package/scripts/smoke/discord-release-workflow.mjs +24 -24
- package/scripts/smoke/git-install-update.mjs +255 -255
- package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
- package/scripts/smoke/live-view-diagnostics.mjs +53 -53
- package/scripts/smoke/live-view-environment.mjs +92 -92
- package/scripts/smoke/live-view-integration.mjs +450 -450
- package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
- package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
- package/scripts/smoke/mobile-ux.mjs +76 -76
- package/scripts/smoke/model-registry.mjs +36 -36
- package/scripts/smoke/multi-project-ui.mjs +45 -45
- package/scripts/smoke/multi-worker-slots.mjs +42 -42
- package/scripts/smoke/notification-center.mjs +87 -87
- package/scripts/smoke/notification-inapp-preference.mjs +23 -23
- package/scripts/smoke/notification-taxonomy.mjs +58 -58
- package/scripts/smoke/orchestration-api.mjs +172 -172
- package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
- package/scripts/smoke/orchestration-live-run.mjs +176 -176
- package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
- package/scripts/smoke/orchestration-model-sync.mjs +30 -30
- package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
- package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
- package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
- package/scripts/smoke/permission-policy.mjs +50 -50
- package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
- package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
- package/scripts/smoke/provider-rest-api.mjs +124 -124
- package/scripts/smoke/provider-selection-status.mjs +52 -52
- package/scripts/smoke/run-state-refresh.mjs +52 -52
- package/scripts/smoke/runtime-manager.mjs +99 -99
- package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
- package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
- package/scripts/smoke/static-root-routing.mjs +21 -21
- package/scripts/smoke/strict-handoff-compact.mjs +60 -60
- package/scripts/smoke/taskmaster-config.mjs +24 -24
- package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
- package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
- package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
- package/scripts/smoke/telegram-control.mjs +331 -331
- package/scripts/smoke/tunnel-persistence.mjs +56 -56
- package/scripts/smoke/update-issue-progress.mjs +69 -69
- package/scripts/smoke/update-ux.mjs +55 -55
- package/scripts/smoke/v138-completion.mjs +132 -132
- package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
- package/scripts/smoke/v138-diagnostics.mjs +63 -63
- package/scripts/smoke/v138-issue-planner.mjs +33 -33
- package/scripts/smoke/v143-remote-control.mjs +76 -76
- package/scripts/smoke/v144-production-loop.mjs +47 -47
- package/scripts/smoke/v145-platformization.mjs +46 -46
- package/scripts/smoke/v146-control-room-ui.mjs +150 -150
- package/scripts/smoke/version-modal-autoshow.mjs +29 -29
- package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
- package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
- package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
- package/scripts/smoke/workflow-templates.mjs +43 -43
- package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
- package/scripts/update-git-install.mjs +298 -298
- package/server/claude-sdk.js +927 -927
- package/server/cli.js +1106 -1106
- package/server/constants/config.js +4 -4
- package/server/cursor-cli.js +344 -344
- package/server/daemon/manager.js +563 -563
- package/server/daemon-manager.js +964 -964
- package/server/database/db.js +988 -988
- package/server/database/json-store.js +197 -197
- package/server/gemini-cli.js +550 -550
- package/server/gemini-response-handler.js +79 -79
- package/server/index.js +5671 -5671
- package/server/load-env.js +35 -35
- package/server/middleware/account-lockout.js +112 -112
- package/server/middleware/auth.js +277 -277
- package/server/middleware/rate-limiter.js +87 -87
- package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
- package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
- package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
- package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
- package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
- package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
- package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -60
- package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -101
- package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
- package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
- package/server/modules/orchestration/a2a/agent-card.ts +55 -55
- package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
- package/server/modules/orchestration/a2a/bus.ts +46 -46
- package/server/modules/orchestration/a2a/routes.ts +586 -586
- package/server/modules/orchestration/a2a/task-dispatcher.ts +345 -345
- package/server/modules/orchestration/a2a/task-store.ts +178 -178
- package/server/modules/orchestration/a2a/types.ts +126 -126
- package/server/modules/orchestration/a2a/validator.ts +113 -113
- package/server/modules/orchestration/index.ts +99 -99
- package/server/modules/orchestration/preview/port-watcher.ts +112 -112
- package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
- package/server/modules/orchestration/preview/types.ts +19 -19
- package/server/modules/orchestration/security/permission-policy.ts +401 -401
- package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
- package/server/modules/orchestration/tasks/orchestration-task.routes.ts +81 -81
- package/server/modules/orchestration/tasks/orchestration-task.service.ts +201 -201
- package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
- package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
- package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
- package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
- package/server/modules/orchestration/workflows/context-packet.ts +186 -186
- package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
- package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
- package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
- package/server/modules/orchestration/workflows/workflow-runner.ts +2062 -2062
- package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
- package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
- package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
- package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
- package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
- package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
- package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
- package/server/modules/orchestration/workspace/path-safety.ts +55 -55
- package/server/modules/orchestration/workspace/types.ts +52 -52
- package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
- package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
- package/server/modules/providers/index.ts +2 -2
- package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
- package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
- package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
- package/server/modules/providers/list/claude/claude.provider.ts +15 -15
- package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
- package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
- package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
- package/server/modules/providers/list/codex/codex.provider.ts +15 -15
- package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
- package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
- package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
- package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
- package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
- package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
- package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
- package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
- package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
- package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
- package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
- package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
- package/server/modules/providers/provider.registry.ts +40 -40
- package/server/modules/providers/provider.routes.ts +982 -982
- package/server/modules/providers/services/mcp.service.ts +86 -86
- package/server/modules/providers/services/provider-auth.service.ts +26 -26
- package/server/modules/providers/services/sessions.service.ts +45 -45
- package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
- package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
- package/server/modules/providers/tests/mcp.test.ts +293 -293
- package/server/openai-codex.js +468 -468
- package/server/opencode-cli.js +491 -491
- package/server/opencode-response-handler.js +111 -111
- package/server/projects.js +3135 -3135
- package/server/qwen-code-cli.js +410 -410
- package/server/routes/agent.js +1462 -1462
- package/server/routes/auth.js +298 -298
- package/server/routes/codex.js +20 -20
- package/server/routes/commands.js +581 -581
- package/server/routes/cursor.js +61 -61
- package/server/routes/diagnostics.js +44 -44
- package/server/routes/gemini.js +25 -25
- package/server/routes/git.js +1822 -1822
- package/server/routes/live-view.js +434 -434
- package/server/routes/mcp-utils.js +13 -13
- package/server/routes/messages.js +97 -97
- package/server/routes/network.js +143 -143
- package/server/routes/platformization.js +231 -231
- package/server/routes/plugins.js +690 -690
- package/server/routes/production-agent-loop.js +90 -90
- package/server/routes/projects.js +918 -918
- package/server/routes/public-api.js +34 -34
- package/server/routes/qwen.js +27 -27
- package/server/routes/remote.js +56 -56
- package/server/routes/settings.js +321 -321
- package/server/routes/telegram.js +163 -163
- package/server/routes/user.js +125 -125
- package/server/routes/webhooks.js +63 -63
- package/server/services/control-room.js +102 -102
- package/server/services/diagnostics.js +165 -165
- package/server/services/external-access.js +403 -403
- package/server/services/install-jobs.js +715 -715
- package/server/services/live-view.js +956 -956
- package/server/services/managed-runtimes.js +493 -493
- package/server/services/model-registry.js +144 -144
- package/server/services/notification-orchestrator.js +365 -365
- package/server/services/notification-taxonomy.js +204 -204
- package/server/services/platformization.js +1052 -1052
- package/server/services/production-agent-loop.js +248 -248
- package/server/services/provider-cli-versions.js +149 -149
- package/server/services/provider-credentials.js +189 -189
- package/server/services/provider-models.js +396 -396
- package/server/services/public-api-manifest.js +181 -181
- package/server/services/qr-login.js +126 -126
- package/server/services/remote-connection.js +127 -127
- package/server/services/runtime-manager.js +323 -323
- package/server/services/startup-update.js +259 -259
- package/server/services/telegram/bot.js +393 -393
- package/server/services/telegram/control-center.js +2453 -2453
- package/server/services/telegram/telegram-gateway.js +314 -314
- package/server/services/telegram/telegram-http-client.js +201 -201
- package/server/services/telegram/translations.js +470 -470
- package/server/services/webhooks.js +216 -216
- package/server/sessionManager.js +225 -225
- package/server/setup-wizard.js +283 -283
- package/server/shared/interfaces.ts +54 -54
- package/server/shared/types.ts +172 -172
- package/server/shared/utils.ts +193 -193
- package/server/tsconfig.json +36 -36
- package/server/utils/colors.js +21 -21
- package/server/utils/commandParser.js +305 -305
- package/server/utils/frontmatter.js +18 -18
- package/server/utils/gitConfig.js +34 -34
- package/server/utils/plugin-loader.js +461 -461
- package/server/utils/plugin-process-manager.js +185 -185
- package/server/utils/port-access.js +227 -227
- package/server/utils/runtime-paths.js +37 -37
- package/server/utils/security-log.js +84 -84
- package/server/utils/url-detection.js +71 -71
- package/server/vite-daemon.js +79 -79
- package/shared/modelConstants.js +161 -161
- package/shared/networkHosts.js +22 -22
|
@@ -1,314 +1,314 @@
|
|
|
1
|
-
import crypto from 'node:crypto';
|
|
2
|
-
|
|
3
|
-
import { telegramLinksDb } from '../../database/db.js';
|
|
4
|
-
|
|
5
|
-
export const TELEGRAM_CONTROL_SCOPES = [
|
|
6
|
-
'admin',
|
|
7
|
-
'telegram:read',
|
|
8
|
-
'telegram:write',
|
|
9
|
-
'providers:read',
|
|
10
|
-
'providers:write',
|
|
11
|
-
'orchestration:read',
|
|
12
|
-
'orchestration:write',
|
|
13
|
-
'projects:read',
|
|
14
|
-
'sessions:read',
|
|
15
|
-
'webhooks:read',
|
|
16
|
-
];
|
|
17
|
-
|
|
18
|
-
export const TELEGRAM_PROVIDERS = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'];
|
|
19
|
-
|
|
20
|
-
export const TELEGRAM_PROGRESS_MODES = ['final', 'steps', 'all', 'errors'];
|
|
21
|
-
|
|
22
|
-
const MAX_TELEGRAM_TEXT = 3600;
|
|
23
|
-
const CONFIRMATION_TTL_MS = 5 * 60 * 1000;
|
|
24
|
-
const DEFAULT_ACTION_TIMEOUT_MS = 10 * 60 * 1000;
|
|
25
|
-
const chatQueues = new Map();
|
|
26
|
-
|
|
27
|
-
export const TELEGRAM_AI_INTENT_ACTIONS = [
|
|
28
|
-
'agent_prompt',
|
|
29
|
-
'show_menu',
|
|
30
|
-
'show_projects',
|
|
31
|
-
'select_project',
|
|
32
|
-
'show_provider_menu',
|
|
33
|
-
'select_provider',
|
|
34
|
-
'show_model_menu',
|
|
35
|
-
'select_model',
|
|
36
|
-
'show_runs',
|
|
37
|
-
'show_approvals',
|
|
38
|
-
'show_workflows',
|
|
39
|
-
'run_workflow',
|
|
40
|
-
'show_sessions',
|
|
41
|
-
'new_chat',
|
|
42
|
-
];
|
|
43
|
-
|
|
44
|
-
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
45
|
-
|
|
46
|
-
export function splitTelegramText(text, max = MAX_TELEGRAM_TEXT) {
|
|
47
|
-
const value = String(text || '').trim();
|
|
48
|
-
if (!value) return [''];
|
|
49
|
-
if (value.length <= max) return [value];
|
|
50
|
-
|
|
51
|
-
const chunks = [];
|
|
52
|
-
let remaining = value;
|
|
53
|
-
while (remaining.length > max) {
|
|
54
|
-
let cut = remaining.lastIndexOf('\n', max);
|
|
55
|
-
if (cut < Math.floor(max * 0.55)) cut = remaining.lastIndexOf(' ', max);
|
|
56
|
-
if (cut < Math.floor(max * 0.55)) cut = max;
|
|
57
|
-
chunks.push(remaining.slice(0, cut).trim());
|
|
58
|
-
remaining = remaining.slice(cut).trim();
|
|
59
|
-
}
|
|
60
|
-
if (remaining) chunks.push(remaining);
|
|
61
|
-
return chunks;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export function normalizeTelegramToolResult(result = {}) {
|
|
65
|
-
if (result?.ok === false) {
|
|
66
|
-
return {
|
|
67
|
-
ok: false,
|
|
68
|
-
message: String(result.message || result.error || 'Action failed.'),
|
|
69
|
-
data: result.data ?? null,
|
|
70
|
-
requiresConfirmation: Boolean(result.requiresConfirmation),
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
return {
|
|
74
|
-
ok: true,
|
|
75
|
-
message: String(result.message || 'OK'),
|
|
76
|
-
data: result.data ?? result,
|
|
77
|
-
requiresConfirmation: Boolean(result.requiresConfirmation),
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function withTimeout(promiseFactory, timeoutMs = DEFAULT_ACTION_TIMEOUT_MS) {
|
|
82
|
-
let timeoutId;
|
|
83
|
-
const timeout = new Promise((_, reject) => {
|
|
84
|
-
timeoutId = setTimeout(() => {
|
|
85
|
-
const error = new Error(`Telegram action timed out after ${timeoutMs}ms`);
|
|
86
|
-
error.code = 'TELEGRAM_ACTION_TIMEOUT';
|
|
87
|
-
reject(error);
|
|
88
|
-
}, timeoutMs);
|
|
89
|
-
});
|
|
90
|
-
return Promise.race([Promise.resolve().then(promiseFactory), timeout])
|
|
91
|
-
.finally(() => clearTimeout(timeoutId));
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function isRetryableError(error) {
|
|
95
|
-
const status = error?.status || error?.statusCode || error?.response?.status || error?.response?.statusCode;
|
|
96
|
-
if ([408, 409, 425, 429, 500, 502, 503, 504].includes(Number(status))) return true;
|
|
97
|
-
const message = String(error?.message || '');
|
|
98
|
-
return /ECONNRESET|ETIMEDOUT|EAI_AGAIN|fetch failed|network/i.test(message);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export async function retryWithBackoff(action, {
|
|
102
|
-
retries = 2,
|
|
103
|
-
baseDelayMs = 500,
|
|
104
|
-
maxDelayMs = 4000,
|
|
105
|
-
shouldRetry = isRetryableError,
|
|
106
|
-
} = {}) {
|
|
107
|
-
let lastError;
|
|
108
|
-
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
109
|
-
try {
|
|
110
|
-
return await action(attempt);
|
|
111
|
-
} catch (error) {
|
|
112
|
-
lastError = error;
|
|
113
|
-
if (attempt >= retries || !shouldRetry(error)) break;
|
|
114
|
-
const delay = Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
|
|
115
|
-
await sleep(delay);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
throw lastError;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function enqueueTelegramJob(chatId, job, { timeoutMs = DEFAULT_ACTION_TIMEOUT_MS } = {}) {
|
|
122
|
-
const key = String(chatId);
|
|
123
|
-
const previous = chatQueues.get(key) || Promise.resolve();
|
|
124
|
-
const current = previous
|
|
125
|
-
.catch(() => {})
|
|
126
|
-
.then(() => withTimeout(job, timeoutMs));
|
|
127
|
-
let queued;
|
|
128
|
-
queued = current.finally(() => {
|
|
129
|
-
if (chatQueues.get(key) === queued) chatQueues.delete(key);
|
|
130
|
-
}).catch(() => {});
|
|
131
|
-
chatQueues.set(key, queued);
|
|
132
|
-
return current;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export async function runTelegramTool({
|
|
136
|
-
userId,
|
|
137
|
-
action,
|
|
138
|
-
execute,
|
|
139
|
-
remoteControlRequired = true,
|
|
140
|
-
timeoutMs = DEFAULT_ACTION_TIMEOUT_MS,
|
|
141
|
-
retries = 1,
|
|
142
|
-
}) {
|
|
143
|
-
const state = telegramLinksDb.getControlState(userId);
|
|
144
|
-
if (remoteControlRequired && state.remoteControlEnabled === false) {
|
|
145
|
-
return normalizeTelegramToolResult({
|
|
146
|
-
ok: false,
|
|
147
|
-
message: 'REMOTE_CONTROL_DISABLED',
|
|
148
|
-
data: { action },
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const data = await retryWithBackoff(
|
|
153
|
-
() => withTimeout(execute, timeoutMs),
|
|
154
|
-
{ retries },
|
|
155
|
-
);
|
|
156
|
-
return normalizeTelegramToolResult({ ok: true, message: 'OK', data });
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export function createTelegramConfirmation(userId, action, payload = {}) {
|
|
160
|
-
const pending = {
|
|
161
|
-
id: crypto.randomBytes(8).toString('hex'),
|
|
162
|
-
action,
|
|
163
|
-
payload,
|
|
164
|
-
expiresAt: new Date(Date.now() + CONFIRMATION_TTL_MS).toISOString(),
|
|
165
|
-
};
|
|
166
|
-
telegramLinksDb.updateControlState(userId, { pendingConfirmation: pending });
|
|
167
|
-
return pending;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
export function consumeTelegramConfirmation(userId, id) {
|
|
171
|
-
const state = telegramLinksDb.getControlState(userId);
|
|
172
|
-
const pending = state.pendingConfirmation;
|
|
173
|
-
if (!pending || pending.id !== id) return { ok: false, reason: 'missing' };
|
|
174
|
-
if (Date.parse(pending.expiresAt) <= Date.now()) {
|
|
175
|
-
telegramLinksDb.updateControlState(userId, { pendingConfirmation: null });
|
|
176
|
-
return { ok: false, reason: 'expired' };
|
|
177
|
-
}
|
|
178
|
-
telegramLinksDb.updateControlState(userId, { pendingConfirmation: null });
|
|
179
|
-
return { ok: true, confirmation: pending };
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export function clearTelegramConfirmation(userId, id = null) {
|
|
183
|
-
const state = telegramLinksDb.getControlState(userId);
|
|
184
|
-
if (id && state.pendingConfirmation?.id !== id) return false;
|
|
185
|
-
telegramLinksDb.updateControlState(userId, { pendingConfirmation: null });
|
|
186
|
-
return true;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export function resolveTelegramProvider(state = {}) {
|
|
190
|
-
const provider = TELEGRAM_PROVIDERS.includes(state.routerProvider)
|
|
191
|
-
? state.routerProvider
|
|
192
|
-
: state.selectedProvider;
|
|
193
|
-
return TELEGRAM_PROVIDERS.includes(provider) ? provider : 'opencode';
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
export function resolveTelegramModel(state = {}) {
|
|
197
|
-
return typeof state.routerModel === 'string' && state.routerModel.trim()
|
|
198
|
-
? state.routerModel.trim()
|
|
199
|
-
: state.selectedModel;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
export function buildTelegramAgentPrompt(prompt, state = {}) {
|
|
203
|
-
const provider = resolveTelegramProvider(state);
|
|
204
|
-
const model = resolveTelegramModel(state);
|
|
205
|
-
const project = state.selectedProjectName || state.selectedProjectPath || 'not selected';
|
|
206
|
-
return [
|
|
207
|
-
'Source: Telegram.',
|
|
208
|
-
`Selected project: ${project}.`,
|
|
209
|
-
`Selected provider: ${provider}${model ? ` / ${model}` : ''}.`,
|
|
210
|
-
'Return a Telegram-friendly final summary with status, relevant IDs, concise output, and any diff/test summary.',
|
|
211
|
-
'Keep the final answer brief unless the user explicitly asks for detail.',
|
|
212
|
-
'',
|
|
213
|
-
'User request:',
|
|
214
|
-
String(prompt || '').trim(),
|
|
215
|
-
].join('\n');
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
function readJsonObjectFromText(text) {
|
|
219
|
-
const value = String(text || '').trim();
|
|
220
|
-
if (!value) return null;
|
|
221
|
-
try {
|
|
222
|
-
const parsed = JSON.parse(value);
|
|
223
|
-
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
224
|
-
} catch {
|
|
225
|
-
const start = value.indexOf('{');
|
|
226
|
-
const end = value.lastIndexOf('}');
|
|
227
|
-
if (start === -1 || end <= start) return null;
|
|
228
|
-
try {
|
|
229
|
-
const parsed = JSON.parse(value.slice(start, end + 1));
|
|
230
|
-
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
231
|
-
} catch {
|
|
232
|
-
return null;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
function readOptionalString(value) {
|
|
238
|
-
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function readConfidence(value) {
|
|
242
|
-
const numeric = Number(value);
|
|
243
|
-
if (!Number.isFinite(numeric)) return 0;
|
|
244
|
-
return Math.max(0, Math.min(1, numeric));
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
export function normalizeTelegramAiIntent(rawIntent, fallbackPrompt = '') {
|
|
248
|
-
const intent = rawIntent && typeof rawIntent === 'object' && !Array.isArray(rawIntent)
|
|
249
|
-
? rawIntent
|
|
250
|
-
: {};
|
|
251
|
-
const action = TELEGRAM_AI_INTENT_ACTIONS.includes(intent.action)
|
|
252
|
-
? intent.action
|
|
253
|
-
: 'agent_prompt';
|
|
254
|
-
const confidence = readConfidence(intent.confidence);
|
|
255
|
-
const safeAction = confidence >= 0.72 ? action : 'agent_prompt';
|
|
256
|
-
const prompt = readOptionalString(intent.prompt) || String(fallbackPrompt || '').trim();
|
|
257
|
-
|
|
258
|
-
return {
|
|
259
|
-
action: safeAction,
|
|
260
|
-
confidence,
|
|
261
|
-
provider: TELEGRAM_PROVIDERS.includes(intent.provider) ? intent.provider : null,
|
|
262
|
-
projectQuery: readOptionalString(intent.projectQuery),
|
|
263
|
-
model: readOptionalString(intent.model),
|
|
264
|
-
workflowInput: readOptionalString(intent.workflowInput) || prompt,
|
|
265
|
-
prompt,
|
|
266
|
-
reply: readOptionalString(intent.reply),
|
|
267
|
-
};
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
export function parseTelegramAiIntentResponse(text, fallbackPrompt = '') {
|
|
271
|
-
return normalizeTelegramAiIntent(readJsonObjectFromText(text), fallbackPrompt);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
export function buildTelegramIntentPrompt(userText, state = {}, context = {}) {
|
|
275
|
-
const provider = resolveTelegramProvider(state);
|
|
276
|
-
const model = resolveTelegramModel(state);
|
|
277
|
-
const project = state.selectedProjectName || state.selectedProjectPath || 'not selected';
|
|
278
|
-
const projects = Array.isArray(context.projects) ? context.projects.slice(0, 12) : [];
|
|
279
|
-
const workflows = Array.isArray(context.workflows) ? context.workflows.slice(0, 12) : [];
|
|
280
|
-
|
|
281
|
-
return [
|
|
282
|
-
'You are the Telegram intent router for Pixcode.',
|
|
283
|
-
'Decide the user intent by meaning, not by matching keywords.',
|
|
284
|
-
'Do not use or describe regex, substring rules, or word-trigger rules.',
|
|
285
|
-
'If the message is casual, ambiguous, asks a broad project/status question, or could be a normal coding request, choose agent_prompt.',
|
|
286
|
-
'Only choose a control action when the user clearly asks to open/change a Pixcode control surface.',
|
|
287
|
-
'Return JSON only. Do not run tools. Do not inspect files. Do not add Markdown.',
|
|
288
|
-
'',
|
|
289
|
-
'Allowed JSON shape:',
|
|
290
|
-
'{"action":"agent_prompt|show_menu|show_projects|select_project|show_provider_menu|select_provider|show_model_menu|select_model|show_runs|show_approvals|show_workflows|run_workflow|show_sessions|new_chat","confidence":0.0,"provider":null,"projectQuery":null,"model":null,"workflowInput":null,"prompt":null,"reply":null}',
|
|
291
|
-
'',
|
|
292
|
-
'Routing policy:',
|
|
293
|
-
'- agent_prompt: default for normal chat, coding work, analysis, debugging, status questions about the repo/server, or unclear text.',
|
|
294
|
-
'- select_provider: only when a provider is explicitly requested as the Telegram provider. provider must be one of the listed providers.',
|
|
295
|
-
'- select_model: only when a concrete model id/name is explicitly requested. model must contain the model id/name.',
|
|
296
|
-
'- select_project: only when a project choice is explicit. projectQuery should be the project name/path the user meant.',
|
|
297
|
-
'- run_workflow: only when the user clearly wants the selected workflow/orchestration to run.',
|
|
298
|
-
'- show_runs/show_approvals/show_workflows/show_projects/show_provider_menu/show_model_menu/show_sessions/show_menu/new_chat: only for clear UI/navigation requests.',
|
|
299
|
-
'- If confidence is below 0.72, set action to agent_prompt.',
|
|
300
|
-
'',
|
|
301
|
-
`Current Telegram provider: ${provider}${model ? ` / ${model}` : ''}.`,
|
|
302
|
-
`Current project: ${project}.`,
|
|
303
|
-
`Available providers: ${TELEGRAM_PROVIDERS.join(', ')}.`,
|
|
304
|
-
projects.length
|
|
305
|
-
? `Known projects: ${projects.map((item) => item.displayName || item.name || item.path).filter(Boolean).join(' | ')}.`
|
|
306
|
-
: 'Known projects: none loaded.',
|
|
307
|
-
workflows.length
|
|
308
|
-
? `Known workflows: ${workflows.map((item) => item.name || item.id).filter(Boolean).join(' | ')}.`
|
|
309
|
-
: 'Known workflows: none loaded.',
|
|
310
|
-
'',
|
|
311
|
-
'User message:',
|
|
312
|
-
String(userText || '').trim(),
|
|
313
|
-
].join('\n');
|
|
314
|
-
}
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
import { telegramLinksDb } from '../../database/db.js';
|
|
4
|
+
|
|
5
|
+
export const TELEGRAM_CONTROL_SCOPES = [
|
|
6
|
+
'admin',
|
|
7
|
+
'telegram:read',
|
|
8
|
+
'telegram:write',
|
|
9
|
+
'providers:read',
|
|
10
|
+
'providers:write',
|
|
11
|
+
'orchestration:read',
|
|
12
|
+
'orchestration:write',
|
|
13
|
+
'projects:read',
|
|
14
|
+
'sessions:read',
|
|
15
|
+
'webhooks:read',
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
export const TELEGRAM_PROVIDERS = ['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'];
|
|
19
|
+
|
|
20
|
+
export const TELEGRAM_PROGRESS_MODES = ['final', 'steps', 'all', 'errors'];
|
|
21
|
+
|
|
22
|
+
const MAX_TELEGRAM_TEXT = 3600;
|
|
23
|
+
const CONFIRMATION_TTL_MS = 5 * 60 * 1000;
|
|
24
|
+
const DEFAULT_ACTION_TIMEOUT_MS = 10 * 60 * 1000;
|
|
25
|
+
const chatQueues = new Map();
|
|
26
|
+
|
|
27
|
+
export const TELEGRAM_AI_INTENT_ACTIONS = [
|
|
28
|
+
'agent_prompt',
|
|
29
|
+
'show_menu',
|
|
30
|
+
'show_projects',
|
|
31
|
+
'select_project',
|
|
32
|
+
'show_provider_menu',
|
|
33
|
+
'select_provider',
|
|
34
|
+
'show_model_menu',
|
|
35
|
+
'select_model',
|
|
36
|
+
'show_runs',
|
|
37
|
+
'show_approvals',
|
|
38
|
+
'show_workflows',
|
|
39
|
+
'run_workflow',
|
|
40
|
+
'show_sessions',
|
|
41
|
+
'new_chat',
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
45
|
+
|
|
46
|
+
export function splitTelegramText(text, max = MAX_TELEGRAM_TEXT) {
|
|
47
|
+
const value = String(text || '').trim();
|
|
48
|
+
if (!value) return [''];
|
|
49
|
+
if (value.length <= max) return [value];
|
|
50
|
+
|
|
51
|
+
const chunks = [];
|
|
52
|
+
let remaining = value;
|
|
53
|
+
while (remaining.length > max) {
|
|
54
|
+
let cut = remaining.lastIndexOf('\n', max);
|
|
55
|
+
if (cut < Math.floor(max * 0.55)) cut = remaining.lastIndexOf(' ', max);
|
|
56
|
+
if (cut < Math.floor(max * 0.55)) cut = max;
|
|
57
|
+
chunks.push(remaining.slice(0, cut).trim());
|
|
58
|
+
remaining = remaining.slice(cut).trim();
|
|
59
|
+
}
|
|
60
|
+
if (remaining) chunks.push(remaining);
|
|
61
|
+
return chunks;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function normalizeTelegramToolResult(result = {}) {
|
|
65
|
+
if (result?.ok === false) {
|
|
66
|
+
return {
|
|
67
|
+
ok: false,
|
|
68
|
+
message: String(result.message || result.error || 'Action failed.'),
|
|
69
|
+
data: result.data ?? null,
|
|
70
|
+
requiresConfirmation: Boolean(result.requiresConfirmation),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
ok: true,
|
|
75
|
+
message: String(result.message || 'OK'),
|
|
76
|
+
data: result.data ?? result,
|
|
77
|
+
requiresConfirmation: Boolean(result.requiresConfirmation),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function withTimeout(promiseFactory, timeoutMs = DEFAULT_ACTION_TIMEOUT_MS) {
|
|
82
|
+
let timeoutId;
|
|
83
|
+
const timeout = new Promise((_, reject) => {
|
|
84
|
+
timeoutId = setTimeout(() => {
|
|
85
|
+
const error = new Error(`Telegram action timed out after ${timeoutMs}ms`);
|
|
86
|
+
error.code = 'TELEGRAM_ACTION_TIMEOUT';
|
|
87
|
+
reject(error);
|
|
88
|
+
}, timeoutMs);
|
|
89
|
+
});
|
|
90
|
+
return Promise.race([Promise.resolve().then(promiseFactory), timeout])
|
|
91
|
+
.finally(() => clearTimeout(timeoutId));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isRetryableError(error) {
|
|
95
|
+
const status = error?.status || error?.statusCode || error?.response?.status || error?.response?.statusCode;
|
|
96
|
+
if ([408, 409, 425, 429, 500, 502, 503, 504].includes(Number(status))) return true;
|
|
97
|
+
const message = String(error?.message || '');
|
|
98
|
+
return /ECONNRESET|ETIMEDOUT|EAI_AGAIN|fetch failed|network/i.test(message);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function retryWithBackoff(action, {
|
|
102
|
+
retries = 2,
|
|
103
|
+
baseDelayMs = 500,
|
|
104
|
+
maxDelayMs = 4000,
|
|
105
|
+
shouldRetry = isRetryableError,
|
|
106
|
+
} = {}) {
|
|
107
|
+
let lastError;
|
|
108
|
+
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
109
|
+
try {
|
|
110
|
+
return await action(attempt);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
lastError = error;
|
|
113
|
+
if (attempt >= retries || !shouldRetry(error)) break;
|
|
114
|
+
const delay = Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
|
|
115
|
+
await sleep(delay);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
throw lastError;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function enqueueTelegramJob(chatId, job, { timeoutMs = DEFAULT_ACTION_TIMEOUT_MS } = {}) {
|
|
122
|
+
const key = String(chatId);
|
|
123
|
+
const previous = chatQueues.get(key) || Promise.resolve();
|
|
124
|
+
const current = previous
|
|
125
|
+
.catch(() => {})
|
|
126
|
+
.then(() => withTimeout(job, timeoutMs));
|
|
127
|
+
let queued;
|
|
128
|
+
queued = current.finally(() => {
|
|
129
|
+
if (chatQueues.get(key) === queued) chatQueues.delete(key);
|
|
130
|
+
}).catch(() => {});
|
|
131
|
+
chatQueues.set(key, queued);
|
|
132
|
+
return current;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export async function runTelegramTool({
|
|
136
|
+
userId,
|
|
137
|
+
action,
|
|
138
|
+
execute,
|
|
139
|
+
remoteControlRequired = true,
|
|
140
|
+
timeoutMs = DEFAULT_ACTION_TIMEOUT_MS,
|
|
141
|
+
retries = 1,
|
|
142
|
+
}) {
|
|
143
|
+
const state = telegramLinksDb.getControlState(userId);
|
|
144
|
+
if (remoteControlRequired && state.remoteControlEnabled === false) {
|
|
145
|
+
return normalizeTelegramToolResult({
|
|
146
|
+
ok: false,
|
|
147
|
+
message: 'REMOTE_CONTROL_DISABLED',
|
|
148
|
+
data: { action },
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const data = await retryWithBackoff(
|
|
153
|
+
() => withTimeout(execute, timeoutMs),
|
|
154
|
+
{ retries },
|
|
155
|
+
);
|
|
156
|
+
return normalizeTelegramToolResult({ ok: true, message: 'OK', data });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function createTelegramConfirmation(userId, action, payload = {}) {
|
|
160
|
+
const pending = {
|
|
161
|
+
id: crypto.randomBytes(8).toString('hex'),
|
|
162
|
+
action,
|
|
163
|
+
payload,
|
|
164
|
+
expiresAt: new Date(Date.now() + CONFIRMATION_TTL_MS).toISOString(),
|
|
165
|
+
};
|
|
166
|
+
telegramLinksDb.updateControlState(userId, { pendingConfirmation: pending });
|
|
167
|
+
return pending;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function consumeTelegramConfirmation(userId, id) {
|
|
171
|
+
const state = telegramLinksDb.getControlState(userId);
|
|
172
|
+
const pending = state.pendingConfirmation;
|
|
173
|
+
if (!pending || pending.id !== id) return { ok: false, reason: 'missing' };
|
|
174
|
+
if (Date.parse(pending.expiresAt) <= Date.now()) {
|
|
175
|
+
telegramLinksDb.updateControlState(userId, { pendingConfirmation: null });
|
|
176
|
+
return { ok: false, reason: 'expired' };
|
|
177
|
+
}
|
|
178
|
+
telegramLinksDb.updateControlState(userId, { pendingConfirmation: null });
|
|
179
|
+
return { ok: true, confirmation: pending };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function clearTelegramConfirmation(userId, id = null) {
|
|
183
|
+
const state = telegramLinksDb.getControlState(userId);
|
|
184
|
+
if (id && state.pendingConfirmation?.id !== id) return false;
|
|
185
|
+
telegramLinksDb.updateControlState(userId, { pendingConfirmation: null });
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function resolveTelegramProvider(state = {}) {
|
|
190
|
+
const provider = TELEGRAM_PROVIDERS.includes(state.routerProvider)
|
|
191
|
+
? state.routerProvider
|
|
192
|
+
: state.selectedProvider;
|
|
193
|
+
return TELEGRAM_PROVIDERS.includes(provider) ? provider : 'opencode';
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function resolveTelegramModel(state = {}) {
|
|
197
|
+
return typeof state.routerModel === 'string' && state.routerModel.trim()
|
|
198
|
+
? state.routerModel.trim()
|
|
199
|
+
: state.selectedModel;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function buildTelegramAgentPrompt(prompt, state = {}) {
|
|
203
|
+
const provider = resolveTelegramProvider(state);
|
|
204
|
+
const model = resolveTelegramModel(state);
|
|
205
|
+
const project = state.selectedProjectName || state.selectedProjectPath || 'not selected';
|
|
206
|
+
return [
|
|
207
|
+
'Source: Telegram.',
|
|
208
|
+
`Selected project: ${project}.`,
|
|
209
|
+
`Selected provider: ${provider}${model ? ` / ${model}` : ''}.`,
|
|
210
|
+
'Return a Telegram-friendly final summary with status, relevant IDs, concise output, and any diff/test summary.',
|
|
211
|
+
'Keep the final answer brief unless the user explicitly asks for detail.',
|
|
212
|
+
'',
|
|
213
|
+
'User request:',
|
|
214
|
+
String(prompt || '').trim(),
|
|
215
|
+
].join('\n');
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function readJsonObjectFromText(text) {
|
|
219
|
+
const value = String(text || '').trim();
|
|
220
|
+
if (!value) return null;
|
|
221
|
+
try {
|
|
222
|
+
const parsed = JSON.parse(value);
|
|
223
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
224
|
+
} catch {
|
|
225
|
+
const start = value.indexOf('{');
|
|
226
|
+
const end = value.lastIndexOf('}');
|
|
227
|
+
if (start === -1 || end <= start) return null;
|
|
228
|
+
try {
|
|
229
|
+
const parsed = JSON.parse(value.slice(start, end + 1));
|
|
230
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
231
|
+
} catch {
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function readOptionalString(value) {
|
|
238
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function readConfidence(value) {
|
|
242
|
+
const numeric = Number(value);
|
|
243
|
+
if (!Number.isFinite(numeric)) return 0;
|
|
244
|
+
return Math.max(0, Math.min(1, numeric));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function normalizeTelegramAiIntent(rawIntent, fallbackPrompt = '') {
|
|
248
|
+
const intent = rawIntent && typeof rawIntent === 'object' && !Array.isArray(rawIntent)
|
|
249
|
+
? rawIntent
|
|
250
|
+
: {};
|
|
251
|
+
const action = TELEGRAM_AI_INTENT_ACTIONS.includes(intent.action)
|
|
252
|
+
? intent.action
|
|
253
|
+
: 'agent_prompt';
|
|
254
|
+
const confidence = readConfidence(intent.confidence);
|
|
255
|
+
const safeAction = confidence >= 0.72 ? action : 'agent_prompt';
|
|
256
|
+
const prompt = readOptionalString(intent.prompt) || String(fallbackPrompt || '').trim();
|
|
257
|
+
|
|
258
|
+
return {
|
|
259
|
+
action: safeAction,
|
|
260
|
+
confidence,
|
|
261
|
+
provider: TELEGRAM_PROVIDERS.includes(intent.provider) ? intent.provider : null,
|
|
262
|
+
projectQuery: readOptionalString(intent.projectQuery),
|
|
263
|
+
model: readOptionalString(intent.model),
|
|
264
|
+
workflowInput: readOptionalString(intent.workflowInput) || prompt,
|
|
265
|
+
prompt,
|
|
266
|
+
reply: readOptionalString(intent.reply),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function parseTelegramAiIntentResponse(text, fallbackPrompt = '') {
|
|
271
|
+
return normalizeTelegramAiIntent(readJsonObjectFromText(text), fallbackPrompt);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function buildTelegramIntentPrompt(userText, state = {}, context = {}) {
|
|
275
|
+
const provider = resolveTelegramProvider(state);
|
|
276
|
+
const model = resolveTelegramModel(state);
|
|
277
|
+
const project = state.selectedProjectName || state.selectedProjectPath || 'not selected';
|
|
278
|
+
const projects = Array.isArray(context.projects) ? context.projects.slice(0, 12) : [];
|
|
279
|
+
const workflows = Array.isArray(context.workflows) ? context.workflows.slice(0, 12) : [];
|
|
280
|
+
|
|
281
|
+
return [
|
|
282
|
+
'You are the Telegram intent router for Pixcode.',
|
|
283
|
+
'Decide the user intent by meaning, not by matching keywords.',
|
|
284
|
+
'Do not use or describe regex, substring rules, or word-trigger rules.',
|
|
285
|
+
'If the message is casual, ambiguous, asks a broad project/status question, or could be a normal coding request, choose agent_prompt.',
|
|
286
|
+
'Only choose a control action when the user clearly asks to open/change a Pixcode control surface.',
|
|
287
|
+
'Return JSON only. Do not run tools. Do not inspect files. Do not add Markdown.',
|
|
288
|
+
'',
|
|
289
|
+
'Allowed JSON shape:',
|
|
290
|
+
'{"action":"agent_prompt|show_menu|show_projects|select_project|show_provider_menu|select_provider|show_model_menu|select_model|show_runs|show_approvals|show_workflows|run_workflow|show_sessions|new_chat","confidence":0.0,"provider":null,"projectQuery":null,"model":null,"workflowInput":null,"prompt":null,"reply":null}',
|
|
291
|
+
'',
|
|
292
|
+
'Routing policy:',
|
|
293
|
+
'- agent_prompt: default for normal chat, coding work, analysis, debugging, status questions about the repo/server, or unclear text.',
|
|
294
|
+
'- select_provider: only when a provider is explicitly requested as the Telegram provider. provider must be one of the listed providers.',
|
|
295
|
+
'- select_model: only when a concrete model id/name is explicitly requested. model must contain the model id/name.',
|
|
296
|
+
'- select_project: only when a project choice is explicit. projectQuery should be the project name/path the user meant.',
|
|
297
|
+
'- run_workflow: only when the user clearly wants the selected workflow/orchestration to run.',
|
|
298
|
+
'- show_runs/show_approvals/show_workflows/show_projects/show_provider_menu/show_model_menu/show_sessions/show_menu/new_chat: only for clear UI/navigation requests.',
|
|
299
|
+
'- If confidence is below 0.72, set action to agent_prompt.',
|
|
300
|
+
'',
|
|
301
|
+
`Current Telegram provider: ${provider}${model ? ` / ${model}` : ''}.`,
|
|
302
|
+
`Current project: ${project}.`,
|
|
303
|
+
`Available providers: ${TELEGRAM_PROVIDERS.join(', ')}.`,
|
|
304
|
+
projects.length
|
|
305
|
+
? `Known projects: ${projects.map((item) => item.displayName || item.name || item.path).filter(Boolean).join(' | ')}.`
|
|
306
|
+
: 'Known projects: none loaded.',
|
|
307
|
+
workflows.length
|
|
308
|
+
? `Known workflows: ${workflows.map((item) => item.name || item.id).filter(Boolean).join(' | ')}.`
|
|
309
|
+
: 'Known workflows: none loaded.',
|
|
310
|
+
'',
|
|
311
|
+
'User message:',
|
|
312
|
+
String(userText || '').trim(),
|
|
313
|
+
].join('\n');
|
|
314
|
+
}
|