@datagrok/grokky 1.0.4 → 1.1.0
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/.claude/skills/deploy-grokky/SKILL.md +193 -0
- package/.grokignore +2 -0
- package/.turbo/turbo-build.log +24 -0
- package/.vscode/settings.json +16 -0
- package/CHANGELOG.md +151 -8
- package/CLAUDE.md +284 -0
- package/CREDITS.md +173 -0
- package/LICENSE.md +16 -0
- package/README.md +24 -0
- package/bdd/bdd.config.json +1 -0
- package/bdd/bindings/elements.ts +9 -0
- package/bdd/bindings/steps.ts +787 -0
- package/bdd/features/ai-panel/platform-work.feature +63 -0
- package/bdd/features/ai-panel/session.feature +69 -0
- package/bdd/features/ai-panel/table-work.feature +99 -0
- package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
- package/bdd/generated/ai-panel/session.test.ts +100 -0
- package/bdd/generated/ai-panel/table-work.test.ts +150 -0
- package/bdd/package.json +1 -0
- package/bdd/tsconfig.json +13 -0
- package/css/ai.css +637 -49
- package/dist/package-test.js +4 -1707
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +742 -92317
- package/dist/package.js.map +1 -1
- package/dockerfiles/claude-runtime/.dockerignore +1 -0
- package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
- package/dockerfiles/claude-runtime/Dockerfile +73 -13
- package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
- package/dockerfiles/claude-runtime/container.json +2 -2
- package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
- package/dockerfiles/claude-runtime/package-lock.json +1721 -306
- package/dockerfiles/claude-runtime/package.json +20 -5
- package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
- package/dockerfiles/claude-runtime/pyproject.toml +18 -0
- package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
- package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
- package/dockerfiles/claude-runtime/src/constants.ts +20 -0
- package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
- package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
- package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
- package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
- package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
- package/dockerfiles/claude-runtime/src/server.ts +134 -234
- package/dockerfiles/claude-runtime/src/session.ts +328 -0
- package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
- package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
- package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
- package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
- package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
- package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
- package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
- package/dockerfiles/claude-runtime/src/types.ts +142 -23
- package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
- package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
- package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
- package/dockerfiles/claude-runtime/src/verify.ts +136 -0
- package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
- package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
- package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
- package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
- package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
- package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
- package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
- package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
- package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
- package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
- package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
- package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
- package/dockerfiles/mcp-server/.eslintrc.json +39 -0
- package/dockerfiles/mcp-server/Dockerfile +10 -2
- package/dockerfiles/mcp-server/package-lock.json +1743 -98
- package/dockerfiles/mcp-server/package.json +27 -5
- package/dockerfiles/mcp-server/src/api-client.ts +123 -66
- package/dockerfiles/mcp-server/src/format.ts +51 -0
- package/dockerfiles/mcp-server/src/index.ts +44 -113
- package/dockerfiles/mcp-server/src/ops.ts +325 -0
- package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
- package/dockerfiles/mcp-server/test/format.test.js +62 -0
- package/dockerfiles/mcp-server/test/ops.test.js +84 -0
- package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
- package/dockerfiles/queue/Dockerfile +2 -0
- package/dockerfiles/queue/container.json +7 -0
- package/docs/AUDIT-2026-08-03.md +1064 -0
- package/docs/BENCHMARK.md +292 -0
- package/docs/CLAUDE_CODE_FLOW.md +746 -0
- package/docs/EXAMPLES.md +82 -0
- package/docs/FEATURES.md +71 -0
- package/docs/IMPLEMENTATION.md +128 -0
- package/docs/LATENCY.md +170 -0
- package/docs/VISION.md +36 -0
- package/files/benchmark/suite.yaml +404 -0
- package/files/scripts/process-cro-results.md +14 -0
- package/files/suggestions.yaml +344 -0
- package/package.json +39 -97
- package/src/ai/ai-window.ts +157 -0
- package/src/ai/benchmark/benchmark.ts +737 -0
- package/src/ai/db-view-functions.ts +56 -0
- package/src/ai/engine.ts +98 -0
- package/src/ai/gemma-engine.ts +81 -0
- package/src/ai/panel.ts +1385 -0
- package/src/ai/prompt-suggestions.ts +209 -0
- package/src/ai/search/combined-search.ts +244 -0
- package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
- package/src/{llm-utils → ai}/storage.ts +0 -1
- package/src/ai/table-tools.ts +145 -0
- package/src/ai/ui.ts +720 -0
- package/src/ai/usage-limiter.ts +105 -0
- package/src/ai/view-tools.ts +352 -0
- package/src/claude/ai-feature.ts +16 -0
- package/src/claude/exec-blocks.ts +176 -0
- package/src/claude/queue-task.ts +84 -0
- package/src/claude/runtime-client.ts +310 -0
- package/src/claude/turn-log.ts +114 -0
- package/src/claude/undoable.ts +105 -0
- package/src/{llm-utils → db}/db-index-tools.ts +24 -32
- package/src/db/sql-tools.ts +336 -0
- package/src/depr/LLM-client.ts +251 -0
- package/src/depr/ai-panel.ts +174 -0
- package/src/depr/chatgpt-assistant.ts +257 -0
- package/src/depr/creds.ts +30 -0
- package/src/depr/deepwikiclient.ts +118 -0
- package/src/depr/indexes/dg-repository-index.ts +266 -0
- package/src/depr/interfaces.ts +170 -0
- package/src/depr/is-help-request.ts +39 -0
- package/src/depr/prompt-engine.ts +52 -0
- package/src/depr/rendering-tools.ts +103 -0
- package/src/depr/script-tools.ts +785 -0
- package/src/depr/tableview-tools.ts +746 -0
- package/src/depr/viewers-ai.ts +67 -0
- package/src/package-api.ts +87 -28
- package/src/package-test.ts +1 -0
- package/src/package.g.ts +98 -48
- package/src/package.ts +211 -157
- package/src/polyfills.ts +12 -0
- package/src/utils.ts +128 -0
- package/tsconfig.json +8 -70
- package/webpack.config.js +3 -49
- package/.eslintignore +0 -2
- package/src/ai-panel.ts +0 -174
- package/src/claude-code/claude-panel.ts +0 -34
- package/src/claude-code/claude-runtime-client.ts +0 -148
- package/src/llm-utils/LLM-client.ts +0 -251
- package/src/llm-utils/combined-search.ts +0 -162
- package/src/llm-utils/creds.ts +0 -30
- package/src/llm-utils/deepwikiclient.ts +0 -118
- package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
- package/src/llm-utils/panel.ts +0 -866
- package/src/llm-utils/script-tools.ts +0 -784
- package/src/llm-utils/sql-tools.ts +0 -840
- package/src/llm-utils/tableview-tools.ts +0 -704
- package/src/llm-utils/ui.ts +0 -315
- package/src/prompt-engine/chatgpt-assistant.ts +0 -257
- package/src/prompt-engine/interfaces.ts +0 -170
- package/src/prompt-engine/prompt-engine.ts +0 -52
- package/src/prompt-engine/rendering-tools.ts +0 -103
- package/src/prompts/is-help-request.ts +0 -26
- package/src/viewers-ai.ts +0 -67
- /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
- /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
- /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
- /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
- /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
- /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
|
@@ -1,238 +1,81 @@
|
|
|
1
|
+
import './privileges';
|
|
1
2
|
import {Hono} from 'hono';
|
|
2
3
|
import {serve} from '@hono/node-server';
|
|
3
4
|
import {createNodeWebSocket} from '@hono/node-ws';
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import
|
|
5
|
+
import type {WSContext} from 'hono/ws';
|
|
6
|
+
import {syncUserFiles} from './sync/orchestrator';
|
|
7
|
+
import {userDirs} from './user/user-dir';
|
|
8
|
+
import {startWorkspaceSync} from './sync/workspace';
|
|
9
|
+
import {buildHelpIndex} from './help-index';
|
|
10
|
+
import {WORKSPACE, apiUrlFromMcpUrl, rewriteForDocker} from './constants';
|
|
11
|
+
import {emit} from './stream-filter';
|
|
12
|
+
import type {WsSender} from './stream-filter';
|
|
13
|
+
import {handleMessage, handleAbort, handleInputResponse, handleDisconnect} from './session';
|
|
14
|
+
import {claimTask, releaseTask} from './tasks';
|
|
15
|
+
import {disposeAll, startPool} from './agent/pool';
|
|
16
|
+
import {CONTAINER_TOKEN_HEADER, userCredentials} from './credentials';
|
|
7
17
|
|
|
8
|
-
const WORKSPACE = process.env['CLAUDE_WORKSPACE'] || '/workspace';
|
|
9
18
|
const PORT = 5355;
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
You are Datagrok Code Assistant — an AI coding agent embedded in the Datagrok data analytics platform.
|
|
14
|
-
You have full access to the Datagrok public repository at ${WORKSPACE}, including the JS API source,
|
|
15
|
-
70+ extension packages, API samples, and documentation.
|
|
16
|
-
|
|
17
|
-
NEVER guess API methods, property names, or function signatures — ALWAYS search the codebase first.
|
|
18
|
-
Key lookup paths: js-api/src/ (core API), packages/ApiSamples/ (usage examples), help/ (docs).
|
|
19
|
-
|
|
20
|
-
## Code Execution
|
|
21
|
-
|
|
22
|
-
When the user asks you to **do** something (add a viewer, modify data, run a script, etc.):
|
|
23
|
-
1. FIRST search the codebase to find the correct API (method names, property names, option keys).
|
|
24
|
-
2. THEN emit the code in a \`\`\`datagrok-exec fenced block — this is the ONLY way code gets executed.
|
|
25
|
-
|
|
26
|
-
NEVER emit a \`\`\`datagrok-exec block with guessed or unverified API calls.
|
|
27
|
-
Regular \`\`\`javascript blocks are for explanations only and will NOT run.
|
|
28
|
-
|
|
29
|
-
### Globals in \`\`\`datagrok-exec blocks
|
|
30
|
-
|
|
31
|
-
| Variable | Type | When available |
|
|
32
|
-
|----------|------|----------------|
|
|
33
|
-
| \`grok\` | module | Always |
|
|
34
|
-
| \`ui\` | module | Always |
|
|
35
|
-
| \`DG\` | module | Always |
|
|
36
|
-
| \`view\` | \`DG.ViewBase\` | Always — check \`view.type\` for specific view type |
|
|
37
|
-
| \`t\` | \`DG.DataFrame\` | Only in TableView (\`view.type === 'TableView'\`) |
|
|
38
|
-
|
|
39
|
-
### Rules
|
|
40
|
-
- \`await\` works directly — the block runs in an async context.
|
|
41
|
-
- Keep blocks short and focused: one action per block.
|
|
42
|
-
- Do NOT import \`grok\`, \`ui\`, or \`DG\` — they are already in scope.
|
|
43
|
-
- Prefer the JS API over console commands or scripts.
|
|
44
|
-
- Keep responses concise.`;
|
|
45
|
-
|
|
46
|
-
const sessions = new Map<string, string>();
|
|
47
|
-
|
|
48
|
-
function storeSession(clientId: string, sdkId: string): void {
|
|
49
|
-
sessions.delete(clientId);
|
|
50
|
-
sessions.set(clientId, sdkId);
|
|
51
|
-
if (sessions.size > MAX_SESSIONS)
|
|
52
|
-
sessions.delete(sessions.keys().next().value!);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function getSession(clientId: string): string | undefined {
|
|
56
|
-
const sid = sessions.get(clientId);
|
|
57
|
-
if (sid !== undefined) {
|
|
58
|
-
sessions.delete(clientId);
|
|
59
|
-
sessions.set(clientId, sid);
|
|
60
|
-
}
|
|
61
|
-
return sid;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
async function* promptStream(message: string) {
|
|
65
|
-
yield {
|
|
66
|
-
type: 'user' as const,
|
|
67
|
-
session_id: '',
|
|
68
|
-
message: {role: 'user' as const, content: message},
|
|
69
|
-
parent_tool_use_id: null,
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function rewriteForDocker(url: string): string {
|
|
74
|
-
return url.replace('//localhost', '//host.docker.internal');
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function buildMcpHeaders(apiKey?: string, apiUrl?: string): Record<string, string> {
|
|
78
|
-
const headers: Record<string, string> = {};
|
|
79
|
-
if (apiKey) {
|
|
80
|
-
headers['Authorization'] = apiKey;
|
|
81
|
-
headers['x-user-api-key'] = apiKey;
|
|
82
|
-
}
|
|
83
|
-
if (apiUrl)
|
|
84
|
-
headers['x-datagrok-api-url'] = apiUrl;
|
|
85
|
-
return headers;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function apiUrlFromMcpUrl(mcpUrl: string): string | undefined {
|
|
89
|
-
const idx = mcpUrl.indexOf('/docker/containers/proxy/');
|
|
90
|
-
return idx > 0 ? mcpUrl.substring(0, idx) : undefined;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function buildOptions(resume?: string, apiKey?: string, mcpServerUrl?: string) {
|
|
94
|
-
const mcpUrl = mcpServerUrl || '';
|
|
95
|
-
const apiUrl = mcpUrl ? apiUrlFromMcpUrl(mcpUrl) : undefined;
|
|
96
|
-
return {
|
|
97
|
-
systemPrompt: DATAGROK_PROMPT,
|
|
98
|
-
allowedTools: ['Read', 'Glob', 'Grep', 'Edit', 'Write', 'Bash', 'WebSearch', 'WebFetch'],
|
|
99
|
-
...(mcpUrl ? {
|
|
100
|
-
mcpServers: {
|
|
101
|
-
datagrok: {
|
|
102
|
-
type: 'http' as const,
|
|
103
|
-
url: mcpUrl,
|
|
104
|
-
headers: buildMcpHeaders(apiKey, apiUrl),
|
|
105
|
-
},
|
|
106
|
-
},
|
|
107
|
-
} : {}),
|
|
108
|
-
permissionMode: 'bypassPermissions' as const,
|
|
109
|
-
allowDangerouslySkipPermissions: true,
|
|
110
|
-
model: 'opus' as const,
|
|
111
|
-
includePartialMessages: true,
|
|
112
|
-
cwd: WORKSPACE,
|
|
113
|
-
...(resume ? {resume} : {}),
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
const toolFormatters: {[K in ToolName]: (i: ToolInputs[K]) => string} = {
|
|
118
|
-
Read: (i) => `Read ${i.file_path ?? ''}`,
|
|
119
|
-
Write: (i) => `Write ${i.file_path ?? ''}`,
|
|
120
|
-
Edit: (i) => `Edit ${i.file_path ?? ''}`,
|
|
121
|
-
Bash: (i) => `Bash: ${(i.command ?? '').slice(0, 120)}`,
|
|
122
|
-
Glob: (i) => `Glob ${i.pattern ?? ''} ${i.path ? 'in ' + i.path : ''}`.trim(),
|
|
123
|
-
Grep: (i) => `Grep '${i.pattern ?? ''}' ${i.path ? 'in ' + i.path : ''}`.trim(),
|
|
124
|
-
WebSearch: (i) => `WebSearch: ${i.query ?? ''}`,
|
|
125
|
-
WebFetch: (i) => `WebFetch: ${i.url ?? ''}`,
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
const mcpFormatters: {[K in McpName]: (i: McpInputs[K]) => string} = {
|
|
129
|
-
call_function: (i) => `Call ${i.name ?? 'function'}`,
|
|
130
|
-
list_functions: (i) => `List functions${i.filter ? ': ' + i.filter : ''}`,
|
|
131
|
-
get_function: (i) => `Get function ${i.id ?? ''}`,
|
|
132
|
-
list_files: (i) => `list files ${i.path ?? ''}`.trim(),
|
|
133
|
-
download_file: (i) => `download file ${i.path ?? ''}`.trim(),
|
|
134
|
-
upload_file: (i) => `upload file ${i.path ?? ''}`.trim(),
|
|
135
|
-
};
|
|
136
|
-
|
|
137
|
-
function toolSummary(name: string, input: Record<string, unknown>): string {
|
|
138
|
-
if (name in toolFormatters)
|
|
139
|
-
return toolFormatters[name as ToolName](input as ToolInputs[ToolName]);
|
|
140
|
-
const mcp = name.replace(/^mcp__[^_]+__/, '');
|
|
141
|
-
if (mcp !== name) {
|
|
142
|
-
if (mcp in mcpFormatters)
|
|
143
|
-
return mcpFormatters[mcp as McpName](input as McpInputs[McpName]);
|
|
144
|
-
return mcp.replace(/_/g, ' ');
|
|
145
|
-
}
|
|
146
|
-
return name;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function extractResult(evt: any): string | null {
|
|
150
|
-
const r = evt.tool_use_result ?? evt.tool_result;
|
|
151
|
-
if (!r)
|
|
152
|
-
return null;
|
|
153
|
-
if (typeof r === 'string')
|
|
154
|
-
return r || null;
|
|
155
|
-
if (Array.isArray(r))
|
|
156
|
-
return r.filter((b: any) => b.type === 'text').map((b: any) => b.text).join('\n') || null;
|
|
157
|
-
return null;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
interface WsSender {
|
|
161
|
-
send(data: string): void;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function emit(ws: WsSender, msg: OutgoingMessage): void {
|
|
165
|
-
ws.send(JSON.stringify(msg));
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
function forwardEvent(ws: WsSender, sid: string, event: SDKMessage): void {
|
|
169
|
-
const e = event as any;
|
|
170
|
-
switch (event.type) {
|
|
171
|
-
case 'system':
|
|
172
|
-
if (event.subtype === 'init' && e.session_id)
|
|
173
|
-
storeSession(sid, e.session_id);
|
|
174
|
-
break;
|
|
175
|
-
case 'assistant':
|
|
176
|
-
for (const block of e.message?.content ?? []) {
|
|
177
|
-
if (block.type === 'tool_use')
|
|
178
|
-
emit(ws, {type: 'tool_activity', sessionId: sid, summary: toolSummary(block.name, block.input ?? {})});
|
|
179
|
-
}
|
|
180
|
-
break;
|
|
181
|
-
case 'user': {
|
|
182
|
-
const content = extractResult(e);
|
|
183
|
-
if (content)
|
|
184
|
-
emit(ws, {type: 'tool_result', sessionId: sid, content});
|
|
185
|
-
break;
|
|
186
|
-
}
|
|
187
|
-
case 'stream_event':
|
|
188
|
-
if (e.event?.delta?.type === 'text_delta' && e.event.delta.text)
|
|
189
|
-
emit(ws, {type: 'chunk', sessionId: sid, content: e.event.delta.text});
|
|
190
|
-
break;
|
|
191
|
-
case 'tool_progress':
|
|
192
|
-
emit(ws, {type: 'tool_activity', sessionId: sid, summary: `Running ${e.tool_name ?? ''}…`});
|
|
193
|
-
break;
|
|
194
|
-
case 'tool_use_summary':
|
|
195
|
-
emit(ws, {type: 'tool_activity', sessionId: sid, summary: e.summary ?? ''});
|
|
196
|
-
break;
|
|
197
|
-
case 'result':
|
|
198
|
-
if (e.subtype === 'success')
|
|
199
|
-
emit(ws, {type: 'final', sessionId: sid, content: e.result || ''});
|
|
200
|
-
else
|
|
201
|
-
emit(ws, {type: 'error', sessionId: sid, message: (e.errors ?? []).join(', ') || e.subtype || 'unknown'});
|
|
202
|
-
break;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
async function handleMessage(ws: WsSender, data: UserMessage): Promise<void> {
|
|
207
|
-
const sid = data.sessionId ?? '';
|
|
208
|
-
const message = data.message ?? '';
|
|
209
|
-
if (!message)
|
|
210
|
-
return emit(ws, {type: 'error', sessionId: sid, message: 'Empty message'});
|
|
211
|
-
|
|
212
|
-
const mcpUrl = rewriteForDocker(data.mcpServerUrl || '');
|
|
213
|
-
|
|
214
|
-
let gotResult = false;
|
|
215
|
-
try {
|
|
216
|
-
const opts = buildOptions(getSession(sid), data.apiKey, mcpUrl);
|
|
217
|
-
for await (const event of query({prompt: promptStream(message), options: opts})) {
|
|
218
|
-
if (event.type === 'result')
|
|
219
|
-
gotResult = true;
|
|
220
|
-
forwardEvent(ws, sid, event);
|
|
221
|
-
}
|
|
222
|
-
} catch (e: any) {
|
|
223
|
-
if (!gotResult || !/exited with code/i.test(String(e.message)))
|
|
224
|
-
emit(ws, {type: 'error', sessionId: sid, message: String(e.message || e)});
|
|
225
|
-
}
|
|
226
|
-
}
|
|
19
|
+
// The life of the container token a connection brings: its credentials are not re-read after that.
|
|
20
|
+
const CREDENTIALS_TTL_MS = 15 * 60_000;
|
|
21
|
+
const KEEPALIVE_MS = 20_000;
|
|
227
22
|
|
|
228
23
|
const app = new Hono();
|
|
229
24
|
const {injectWebSocket, upgradeWebSocket} = createNodeWebSocket({app});
|
|
230
25
|
|
|
231
26
|
app.get('/health', (c) => c.json({status: 'ok'}));
|
|
232
27
|
|
|
233
|
-
|
|
234
|
-
|
|
28
|
+
// Admission-task long-poll for the queued route (see tasks.ts). The celery worker
|
|
29
|
+
// re-polls while the answer is {status: 'running'}; any other status ends its task.
|
|
30
|
+
app.post('/task/claim', async (c) => {
|
|
31
|
+
const {taskId, sessionId} = await c.req.json();
|
|
32
|
+
if (!taskId || !sessionId)
|
|
33
|
+
return c.json({error: 'taskId and sessionId are required'}, 400);
|
|
34
|
+
return c.json(await claimTask(taskId, sessionId));
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// Task revoked platform-side: free the slot and abort the turn it was admitting.
|
|
38
|
+
app.post('/task/release', async (c) => {
|
|
39
|
+
const {taskId} = await c.req.json();
|
|
40
|
+
const sessionId = releaseTask(taskId ?? '');
|
|
41
|
+
if (sessionId)
|
|
42
|
+
handleDisconnect([sessionId]);
|
|
43
|
+
return c.json({status: 'released'});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
app.get('/ws', upgradeWebSocket((c) => {
|
|
47
|
+
// The token comes only with the handshake. A connection whose lookup failed, or whose credentials have outlived
|
|
48
|
+
// the token, is closed once idle: the browser's next prompt reconnects and the credentials are read again.
|
|
49
|
+
const credentials = userCredentials(c.req.header(CONTAINER_TOKEN_HEADER));
|
|
50
|
+
let stale = false;
|
|
51
|
+
let turns = 0;
|
|
52
|
+
let socket: WSContext | undefined;
|
|
53
|
+
const closeIfStale = () => {
|
|
54
|
+
if (stale && !turns)
|
|
55
|
+
socket?.close(1000, 'Credentials refresh');
|
|
56
|
+
};
|
|
57
|
+
credentials.catch((e: Error) => {
|
|
58
|
+
console.warn(`credentials: ${e.message}`);
|
|
59
|
+
stale = true;
|
|
60
|
+
});
|
|
61
|
+
const expiry = setTimeout(() => {
|
|
62
|
+
stale = true;
|
|
63
|
+
closeIfStale();
|
|
64
|
+
}, CREDENTIALS_TTL_MS);
|
|
65
|
+
const sessionIds = new Set<string>();
|
|
66
|
+
const keepalive = setInterval(() => {
|
|
67
|
+
if (turns)
|
|
68
|
+
socket?.send(JSON.stringify({type: 'keepalive'}));
|
|
69
|
+
}, KEEPALIVE_MS);
|
|
70
|
+
const disconnect = (_evt: unknown, ws: WsSender) => {
|
|
71
|
+
clearTimeout(expiry);
|
|
72
|
+
clearInterval(keepalive);
|
|
73
|
+
handleDisconnect(sessionIds, ws);
|
|
74
|
+
};
|
|
235
75
|
return {
|
|
76
|
+
onOpen(_evt: Event, ws: WSContext) {
|
|
77
|
+
socket = ws;
|
|
78
|
+
},
|
|
236
79
|
onMessage(evt: any, ws: any) {
|
|
237
80
|
const sender = ws as unknown as WsSender;
|
|
238
81
|
let data: any;
|
|
@@ -242,6 +85,42 @@ app.get('/ws', upgradeWebSocket(() => {
|
|
|
242
85
|
return emit(sender, {type: 'error', sessionId: '', message: 'Invalid JSON'});
|
|
243
86
|
}
|
|
244
87
|
|
|
88
|
+
if (data.apiKey && (data.type === 'user_message' || data.type === 'sync_user_files')) {
|
|
89
|
+
userDirs.ensureDir(data.apiKey, apiUrlFromMcpUrl(rewriteForDocker(data.mcpServerUrl || ''))).catch((e: any) =>
|
|
90
|
+
console.warn(`user-dir pre-hook (${data.type}, session ${data.sessionId ?? '?'}):`, e.message));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (data.type === 'abort') {
|
|
94
|
+
handleAbort(sender, data);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (data.type === 'input_response') {
|
|
99
|
+
handleInputResponse(sender, data);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (data.type === 'sync_user_files') {
|
|
104
|
+
const mcpUrl = rewriteForDocker(data.mcpServerUrl || '');
|
|
105
|
+
const apiUrl = apiUrlFromMcpUrl(mcpUrl);
|
|
106
|
+
if (apiUrl && data.apiKey) {
|
|
107
|
+
const scope = data.scope || 'all';
|
|
108
|
+
const packageName = data.packageName;
|
|
109
|
+
console.log(`sync_user_files: scope=${scope}, packageName=${packageName ?? '<none>'}`);
|
|
110
|
+
(async () => {
|
|
111
|
+
try {
|
|
112
|
+
const result = await syncUserFiles(apiUrl, data.apiKey, scope, packageName);
|
|
113
|
+
console.log(`sync_user_files: synced ${result.files.length} file(s) (scope=${scope})`);
|
|
114
|
+
emit(sender, {type: 'sync_status', status: 'done', files: result.files});
|
|
115
|
+
} catch (e: any) {
|
|
116
|
+
console.warn('sync_user_files failed:', e.message);
|
|
117
|
+
emit(sender, {type: 'sync_status', status: 'error', message: e.message});
|
|
118
|
+
}
|
|
119
|
+
})();
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
245
124
|
if (data.type !== 'user_message') {
|
|
246
125
|
return emit(sender, {
|
|
247
126
|
type: 'error', sessionId: data.sessionId ?? '',
|
|
@@ -249,25 +128,46 @@ app.get('/ws', upgradeWebSocket(() => {
|
|
|
249
128
|
});
|
|
250
129
|
}
|
|
251
130
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
131
|
+
sessionIds.add(data.sessionId ?? '');
|
|
132
|
+
turns++;
|
|
133
|
+
handleMessage(sender, data, credentials).catch((e: any) =>
|
|
134
|
+
emit(sender, {type: 'error', sessionId: data.sessionId ?? '', message: String(e?.message ?? e)}))
|
|
135
|
+
.finally(() => {
|
|
136
|
+
turns--;
|
|
137
|
+
closeIfStale();
|
|
256
138
|
});
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
busy = true;
|
|
260
|
-
handleMessage(sender, data).finally(() => { busy = false; });
|
|
261
139
|
},
|
|
140
|
+
onClose: disconnect,
|
|
141
|
+
onError: disconnect,
|
|
262
142
|
};
|
|
263
143
|
}));
|
|
264
144
|
|
|
265
145
|
app.notFound((c) => c.json({error: 'Not found'}, 404));
|
|
266
146
|
app.onError((err, c) => c.json({error: String(err)}, 500));
|
|
267
147
|
|
|
268
|
-
|
|
269
|
-
|
|
148
|
+
// Survive stray rejections (e.g. abort races) instead of letting Node kill the container.
|
|
149
|
+
process.on('unhandledRejection', (reason) => console.error('unhandledRejection (survived):', reason));
|
|
150
|
+
process.on('uncaughtException', (err) => console.error('uncaughtException (survived):', err));
|
|
151
|
+
// Agent processes run in their own process groups, so they do not die with this one on their own.
|
|
152
|
+
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
|
|
153
|
+
process.on(signal, () => {
|
|
154
|
+
disposeAll(signal);
|
|
155
|
+
process.exit(0);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
270
158
|
|
|
271
|
-
const server = serve({fetch: app.fetch, port: PORT});
|
|
159
|
+
const server = serve({fetch: app.fetch, port: PORT}, () => startPool());
|
|
272
160
|
injectWebSocket(server);
|
|
161
|
+
startWorkspaceSync();
|
|
162
|
+
try {
|
|
163
|
+
buildHelpIndex(WORKSPACE);
|
|
164
|
+
} catch (e: any) {
|
|
165
|
+
console.warn('help-index: build failed:', e.message);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (!process.env.DATAGROK_API_URL) {
|
|
169
|
+
console.warn('DATAGROK_API_URL is not set: ' +
|
|
170
|
+
'identity verification will trust the first client-supplied URL (dev only)');
|
|
171
|
+
}
|
|
172
|
+
|
|
273
173
|
console.log(`claude-runtime listening on :${PORT}`);
|