@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.
Files changed (203) hide show
  1. package/.claude/skills/deploy-grokky/SKILL.md +193 -0
  2. package/.grokignore +2 -0
  3. package/.turbo/turbo-build.log +24 -0
  4. package/.vscode/settings.json +16 -0
  5. package/CHANGELOG.md +151 -8
  6. package/CLAUDE.md +284 -0
  7. package/CREDITS.md +173 -0
  8. package/LICENSE.md +16 -0
  9. package/README.md +24 -0
  10. package/bdd/bdd.config.json +1 -0
  11. package/bdd/bindings/elements.ts +9 -0
  12. package/bdd/bindings/steps.ts +787 -0
  13. package/bdd/features/ai-panel/platform-work.feature +63 -0
  14. package/bdd/features/ai-panel/session.feature +69 -0
  15. package/bdd/features/ai-panel/table-work.feature +99 -0
  16. package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
  17. package/bdd/generated/ai-panel/session.test.ts +100 -0
  18. package/bdd/generated/ai-panel/table-work.test.ts +150 -0
  19. package/bdd/package.json +1 -0
  20. package/bdd/tsconfig.json +13 -0
  21. package/css/ai.css +637 -49
  22. package/dist/package-test.js +4 -1707
  23. package/dist/package-test.js.map +1 -1
  24. package/dist/package.js +742 -92317
  25. package/dist/package.js.map +1 -1
  26. package/dockerfiles/claude-runtime/.dockerignore +1 -0
  27. package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
  28. package/dockerfiles/claude-runtime/Dockerfile +73 -13
  29. package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
  30. package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
  31. package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
  32. package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
  33. package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
  34. package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
  35. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
  36. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
  37. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
  38. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
  39. package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
  40. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
  41. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
  42. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
  43. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
  44. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
  45. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
  46. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
  47. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
  48. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
  49. package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
  50. package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
  51. package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
  52. package/dockerfiles/claude-runtime/container.json +2 -2
  53. package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
  54. package/dockerfiles/claude-runtime/package-lock.json +1721 -306
  55. package/dockerfiles/claude-runtime/package.json +20 -5
  56. package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
  57. package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
  58. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
  59. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
  60. package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
  61. package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
  62. package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
  63. package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
  64. package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
  65. package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
  66. package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
  67. package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
  68. package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
  69. package/dockerfiles/claude-runtime/pyproject.toml +18 -0
  70. package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
  71. package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
  72. package/dockerfiles/claude-runtime/src/constants.ts +20 -0
  73. package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
  74. package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
  75. package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
  76. package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
  77. package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
  78. package/dockerfiles/claude-runtime/src/server.ts +134 -234
  79. package/dockerfiles/claude-runtime/src/session.ts +328 -0
  80. package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
  81. package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
  82. package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
  83. package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
  84. package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
  85. package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
  86. package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
  87. package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
  88. package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
  89. package/dockerfiles/claude-runtime/src/types.ts +142 -23
  90. package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
  91. package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
  92. package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
  93. package/dockerfiles/claude-runtime/src/verify.ts +136 -0
  94. package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
  95. package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
  96. package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
  97. package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
  98. package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
  99. package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
  100. package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
  101. package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
  102. package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
  103. package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
  104. package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
  105. package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
  106. package/dockerfiles/mcp-server/.eslintrc.json +39 -0
  107. package/dockerfiles/mcp-server/Dockerfile +10 -2
  108. package/dockerfiles/mcp-server/package-lock.json +1743 -98
  109. package/dockerfiles/mcp-server/package.json +27 -5
  110. package/dockerfiles/mcp-server/src/api-client.ts +123 -66
  111. package/dockerfiles/mcp-server/src/format.ts +51 -0
  112. package/dockerfiles/mcp-server/src/index.ts +44 -113
  113. package/dockerfiles/mcp-server/src/ops.ts +325 -0
  114. package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
  115. package/dockerfiles/mcp-server/test/format.test.js +62 -0
  116. package/dockerfiles/mcp-server/test/ops.test.js +84 -0
  117. package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
  118. package/dockerfiles/queue/Dockerfile +2 -0
  119. package/dockerfiles/queue/container.json +7 -0
  120. package/docs/AUDIT-2026-08-03.md +1064 -0
  121. package/docs/BENCHMARK.md +292 -0
  122. package/docs/CLAUDE_CODE_FLOW.md +746 -0
  123. package/docs/EXAMPLES.md +82 -0
  124. package/docs/FEATURES.md +71 -0
  125. package/docs/IMPLEMENTATION.md +128 -0
  126. package/docs/LATENCY.md +170 -0
  127. package/docs/VISION.md +36 -0
  128. package/files/benchmark/suite.yaml +404 -0
  129. package/files/scripts/process-cro-results.md +14 -0
  130. package/files/suggestions.yaml +344 -0
  131. package/package.json +39 -97
  132. package/src/ai/ai-window.ts +157 -0
  133. package/src/ai/benchmark/benchmark.ts +737 -0
  134. package/src/ai/db-view-functions.ts +56 -0
  135. package/src/ai/engine.ts +98 -0
  136. package/src/ai/gemma-engine.ts +81 -0
  137. package/src/ai/panel.ts +1385 -0
  138. package/src/ai/prompt-suggestions.ts +209 -0
  139. package/src/ai/search/combined-search.ts +244 -0
  140. package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
  141. package/src/{llm-utils → ai}/storage.ts +0 -1
  142. package/src/ai/table-tools.ts +145 -0
  143. package/src/ai/ui.ts +720 -0
  144. package/src/ai/usage-limiter.ts +105 -0
  145. package/src/ai/view-tools.ts +352 -0
  146. package/src/claude/ai-feature.ts +16 -0
  147. package/src/claude/exec-blocks.ts +176 -0
  148. package/src/claude/queue-task.ts +84 -0
  149. package/src/claude/runtime-client.ts +310 -0
  150. package/src/claude/turn-log.ts +114 -0
  151. package/src/claude/undoable.ts +105 -0
  152. package/src/{llm-utils → db}/db-index-tools.ts +24 -32
  153. package/src/db/sql-tools.ts +336 -0
  154. package/src/depr/LLM-client.ts +251 -0
  155. package/src/depr/ai-panel.ts +174 -0
  156. package/src/depr/chatgpt-assistant.ts +257 -0
  157. package/src/depr/creds.ts +30 -0
  158. package/src/depr/deepwikiclient.ts +118 -0
  159. package/src/depr/indexes/dg-repository-index.ts +266 -0
  160. package/src/depr/interfaces.ts +170 -0
  161. package/src/depr/is-help-request.ts +39 -0
  162. package/src/depr/prompt-engine.ts +52 -0
  163. package/src/depr/rendering-tools.ts +103 -0
  164. package/src/depr/script-tools.ts +785 -0
  165. package/src/depr/tableview-tools.ts +746 -0
  166. package/src/depr/viewers-ai.ts +67 -0
  167. package/src/package-api.ts +87 -28
  168. package/src/package-test.ts +1 -0
  169. package/src/package.g.ts +98 -48
  170. package/src/package.ts +211 -157
  171. package/src/polyfills.ts +12 -0
  172. package/src/utils.ts +128 -0
  173. package/tsconfig.json +8 -70
  174. package/webpack.config.js +3 -49
  175. package/.eslintignore +0 -2
  176. package/src/ai-panel.ts +0 -174
  177. package/src/claude-code/claude-panel.ts +0 -34
  178. package/src/claude-code/claude-runtime-client.ts +0 -148
  179. package/src/llm-utils/LLM-client.ts +0 -251
  180. package/src/llm-utils/combined-search.ts +0 -162
  181. package/src/llm-utils/creds.ts +0 -30
  182. package/src/llm-utils/deepwikiclient.ts +0 -118
  183. package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
  184. package/src/llm-utils/panel.ts +0 -866
  185. package/src/llm-utils/script-tools.ts +0 -784
  186. package/src/llm-utils/sql-tools.ts +0 -840
  187. package/src/llm-utils/tableview-tools.ts +0 -704
  188. package/src/llm-utils/ui.ts +0 -315
  189. package/src/prompt-engine/chatgpt-assistant.ts +0 -257
  190. package/src/prompt-engine/interfaces.ts +0 -170
  191. package/src/prompt-engine/prompt-engine.ts +0 -52
  192. package/src/prompt-engine/rendering-tools.ts +0 -103
  193. package/src/prompts/is-help-request.ts +0 -26
  194. package/src/viewers-ai.ts +0 -67
  195. /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
  196. /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
  197. /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
  198. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
  199. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
  200. /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
  201. /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
  202. /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
  203. /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
@@ -0,0 +1,214 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import {runWithContext, request} from '../shared-api-client';
4
+ import {resolveHomeConnection, syncHomeFiles} from './home-files';
5
+ import {syncPackages} from './packages';
6
+ import {syncSharedConnections} from './shared-connections';
7
+ import {getInstalledPackages} from '../user/installed-packages';
8
+ import {userDirs} from '../user/user-dir';
9
+ import {buildStagedWorkspace} from '../user/staged-workspace';
10
+
11
+ // ── Shared types ───────────────────────────────────────────────────────
12
+
13
+ export interface EntityTag {
14
+ id?: string;
15
+ tag: string;
16
+ type?: string | null;
17
+ }
18
+
19
+ export interface ConnectionInfo {
20
+ id: string;
21
+ name: string;
22
+ namespace?: string;
23
+ entityTags?: EntityTag[];
24
+ }
25
+
26
+ export interface RemoteFileEntry {
27
+ path: string; // relative path from the root dir, e.g. "subdir/file.md"
28
+ updatedOn: string; // ISO timestamp from the server
29
+ }
30
+
31
+ // Response shape from the Datagrok connectors file-listing API (FileInfo in Dart).
32
+ interface FileEntry {
33
+ name?: string;
34
+ friendlyName?: string;
35
+ isFile?: boolean;
36
+ updatedOn?: string;
37
+ }
38
+
39
+ // ── Shared utilities ───────────────────────────────────────────────────
40
+
41
+ export function connectorPath(conn: ConnectionInfo): string {
42
+ const ns = conn.namespace ?? 'System:';
43
+ return ns.endsWith(':') ? `${ns}${conn.name}` : `${ns}:${conn.name}`;
44
+ }
45
+
46
+ export async function collectFiles(connId: string, dirPath: string): Promise<RemoteFileEntry[]> {
47
+ let entries: FileEntry[];
48
+ try {
49
+ const filePath = dirPath ? `${dirPath.replace(/^\//, '')}/` : '';
50
+ entries = await request<FileEntry[]>('GET', `/connectors/connections/${connId}/files/${filePath}`);
51
+ } catch (e: any) {
52
+ console.warn(`user-files: failed to list ${dirPath}:`, e.message);
53
+ return [];
54
+ }
55
+
56
+ if (!Array.isArray(entries))
57
+ return [];
58
+
59
+ const files: RemoteFileEntry[] = [];
60
+ for (const entry of entries) {
61
+ const name = entry.name ?? entry.friendlyName ?? '';
62
+ if (!name)
63
+ continue;
64
+ const rel = dirPath ? `${dirPath}/${name}` : name;
65
+ if (!entry.isFile) {
66
+ console.log(`user-files: descending into directory ${rel}`);
67
+ files.push(...await collectFiles(connId, rel));
68
+ } else
69
+ files.push({path: rel, updatedOn: entry.updatedOn ?? ''});
70
+ }
71
+ return files;
72
+ }
73
+
74
+ // ── List agent files on disk ───────────────────────────────────────────
75
+
76
+ async function listAgentFiles(userDir: string): Promise<string[]> {
77
+ const agentsDir = path.join(userDir, 'agents');
78
+ try {
79
+ const entries = await fs.readdir(agentsDir, {recursive: true, withFileTypes: true});
80
+ const files: string[] = [];
81
+ for (const entry of entries) {
82
+ if (!entry.isFile())
83
+ continue;
84
+ files.push(path.relative(agentsDir, path.join(entry.parentPath, entry.name)));
85
+ }
86
+ console.log(`user-files: listed ${files.length} agent file(s) on disk`);
87
+ return files;
88
+ } catch {
89
+ return [];
90
+ }
91
+ }
92
+
93
+ // ── Sync orchestration ─────────────────────────────────────────────────
94
+
95
+ const syncInFlight = new Map<string, Promise<{dir: string; files: string[]}>>();
96
+ // apiKey → epoch ms of the last full ('all') sync. Drives the on-demand TTL refresh.
97
+ const lastFullSync = new Map<string, number>();
98
+ const REFRESH_TTL_MS = 15 * 60 * 1000;
99
+
100
+ export type SyncScope = 'all' | 'user-files' | 'packages' | 'shared';
101
+
102
+ export async function syncUserFiles(
103
+ apiUrl: string, apiKey: string, scope: SyncScope = 'all', packageName?: string,
104
+ ): Promise<{dir: string; files: string[]}> {
105
+ const dir = userDirs.dirFromId(await userDirs.resolveUserId(apiKey, apiUrl));
106
+
107
+ // scope 'all' = a Claude query is starting (chat, panel, or search — all route
108
+ // through handleMessage). After the first full sync, serve disk immediately and
109
+ // refresh remote sources in the background once the TTL has elapsed, so a turn
110
+ // never pays sync latency. Freshness lags by at most one turn — fine for
111
+ // low-churn shared skills / package agents.
112
+ if (scope === 'all' && lastFullSync.has(apiKey)) {
113
+ const age = Date.now() - lastFullSync.get(apiKey)!;
114
+ if (age > REFRESH_TTL_MS && !syncInFlight.has(apiKey)) {
115
+ console.log('user-files: refresh TTL elapsed — refreshing packages + shared in background');
116
+ const refresh = (async () => {
117
+ // This user's own agent-folder edits are caught by the package.ts file
118
+ // listeners; the recurring refresh only needs remote-actor changes.
119
+ await doSync(apiUrl, apiKey, 'shared');
120
+ await doSync(apiUrl, apiKey, 'packages');
121
+ lastFullSync.set(apiKey, Date.now());
122
+ return {dir, files: await listAgentFiles(dir)};
123
+ })();
124
+ syncInFlight.set(apiKey, refresh);
125
+ refresh
126
+ .catch((e: any) => console.warn('user-files: background refresh failed:', e.message))
127
+ .finally(() => {
128
+ if (syncInFlight.get(apiKey) === refresh)
129
+ syncInFlight.delete(apiKey);
130
+ });
131
+ }
132
+ return {dir, files: await listAgentFiles(dir)};
133
+ }
134
+
135
+ // First 'all' sync (blocking, so files exist for this turn) or an explicit
136
+ // partial scope from an event ('user-files' / 'packages' / 'shared').
137
+ const existing = syncInFlight.get(apiKey);
138
+ if (existing && scope === 'all') {
139
+ console.log('user-files: sync already in flight, awaiting...');
140
+ return existing;
141
+ }
142
+
143
+ const promise = doSync(apiUrl, apiKey, scope, packageName);
144
+ syncInFlight.set(apiKey, promise);
145
+ try {
146
+ return await promise;
147
+ } finally {
148
+ if (syncInFlight.get(apiKey) === promise)
149
+ syncInFlight.delete(apiKey);
150
+ }
151
+ }
152
+
153
+ async function doSync(
154
+ apiUrl: string, apiKey: string, scope: SyncScope, packageName?: string,
155
+ ): Promise<{dir: string; files: string[]}> {
156
+ const userId = await userDirs.resolveUserId(apiKey, apiUrl);
157
+ const dir = userDirs.dirFromId(userId);
158
+ console.log(`user-files: starting sync for user ${userId} (scope=${scope})`);
159
+
160
+ await userDirs.ensureDir(apiKey, apiUrl);
161
+
162
+ let homeConnId: string | null = null;
163
+ if (scope === 'all' || scope === 'user-files') {
164
+ await runWithContext({apiKey, apiUrl}, async () => {
165
+ const home = await resolveHomeConnection();
166
+ if (!home) {
167
+ console.log('user-files: skipping user file sync (no Home connection)');
168
+ return;
169
+ }
170
+ homeConnId = home.connId;
171
+ const downloaded = await syncHomeFiles(dir, home.connId, home.connectorPath);
172
+ if (downloaded.length)
173
+ console.log(`user-files: synced ${downloaded.length} user file(s)`);
174
+ else
175
+ console.log('user-files: all user files up-to-date');
176
+ });
177
+ }
178
+
179
+ if (scope === 'all' || scope === 'shared') {
180
+ await runWithContext({apiKey, apiUrl}, async () => {
181
+ try {
182
+ await syncSharedConnections(dir, homeConnId);
183
+ } catch (e: any) {
184
+ console.warn('shared-connections: sync failed:', e.message);
185
+ }
186
+ });
187
+ }
188
+
189
+ if (scope === 'all' || scope === 'packages') {
190
+ await runWithContext({apiKey, apiUrl}, async () => {
191
+ try {
192
+ await syncPackages(dir, packageName);
193
+ } catch (e: any) {
194
+ console.warn('package-agents: sync failed:', e.message);
195
+ }
196
+ });
197
+
198
+ const installed = getInstalledPackages(userId);
199
+ if (installed) {
200
+ try {
201
+ await buildStagedWorkspace(dir, installed.keys());
202
+ } catch (e: any) {
203
+ console.warn('staged-workspace: build failed:', e.message);
204
+ }
205
+ }
206
+ }
207
+
208
+ if (scope === 'all')
209
+ lastFullSync.set(apiKey, Date.now());
210
+
211
+ const files = await listAgentFiles(dir);
212
+ console.log(`user-files: sync complete — ${files.length} total agent file(s)`);
213
+ return {dir, files};
214
+ }
@@ -0,0 +1,145 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import {request, requestBinary, listPackageFolder} from '../shared-api-client';
4
+ import {WORKSPACE} from '../constants';
5
+ import {setInstalledPackages} from '../user/installed-packages';
6
+
7
+ export interface PackageInfo {
8
+ id: string;
9
+ name: string;
10
+ version: string;
11
+ buildHash: string;
12
+ buildNumber: number;
13
+ updatedOn?: string;
14
+ }
15
+
16
+ interface CacheEntry {
17
+ buildHash: string;
18
+ files: string[];
19
+ }
20
+
21
+ // Per-user, per-process cache: userId → (packageName → {buildHash, synced files}).
22
+ // In-memory only — /users is container-ephemeral, so persisting it would buy nothing.
23
+ const cache = new Map<string, Map<string, CacheEntry>>();
24
+
25
+ const SYNC_CONCURRENCY = 8;
26
+
27
+ let workspacePackages: Set<string> | null = null;
28
+
29
+ async function getWorkspacePackages(): Promise<Set<string>> {
30
+ if (workspacePackages)
31
+ return workspacePackages;
32
+ try {
33
+ const entries = await fs.readdir(path.join(WORKSPACE, 'packages'), {withFileTypes: true});
34
+ workspacePackages = new Set(entries.filter((e) => e.isDirectory()).map((e) => e.name.toLowerCase()));
35
+ console.log(`package-agents: found ${workspacePackages.size} workspace package(s)`);
36
+ } catch {
37
+ workspacePackages = new Set();
38
+ }
39
+ return workspacePackages;
40
+ }
41
+
42
+ // Syncs one package's agents/ folder. Only fetches when the build changed.
43
+ async function syncSinglePackage(userDir: string, pkg: PackageInfo, userCache: Map<string, CacheEntry>): Promise<void> {
44
+ const prev = userCache.get(pkg.name);
45
+ if (prev?.buildHash === pkg.buildHash) {
46
+ console.log(`package-agents: ${pkg.name} up-to-date (build=${pkg.buildHash}), skipping`);
47
+ return;
48
+ }
49
+
50
+ console.log(`package-agents: syncing ${pkg.name} (build=${pkg.buildHash})`);
51
+ const base = `/packages/published/files/${pkg.name}/${pkg.version}/${pkg.buildHash}/${pkg.buildNumber}`;
52
+ const children = await listPackageFolder(`${base}/agents/`);
53
+ const agentsDir = path.join(userDir, 'agents');
54
+
55
+ // Drop the previous build's files before writing the current ones.
56
+ if (prev?.files.length) {
57
+ for (const f of prev.files)
58
+ await fs.rm(path.join(agentsDir, f), {force: true});
59
+ console.log(`package-agents: removed ${prev.files.length} old file(s) for ${pkg.name}`);
60
+ }
61
+
62
+ if (!children?.length) {
63
+ userCache.set(pkg.name, {buildHash: pkg.buildHash, files: []});
64
+ console.log(`package-agents: ${pkg.name} has no agents/ files`);
65
+ return;
66
+ }
67
+
68
+ await fs.mkdir(agentsDir, {recursive: true});
69
+ const files: string[] = [];
70
+ for (const child of children) {
71
+ if (child.endsWith('/')) {
72
+ console.warn(`package-agents: ${pkg.name} skipping nested agents folder ${child}`);
73
+ continue;
74
+ }
75
+ const buf = await requestBinary('GET', `${base}/agents/${child}`);
76
+ const dest = `${pkg.name}-${child}`;
77
+ await fs.writeFile(path.join(agentsDir, dest), buf);
78
+ files.push(dest);
79
+ }
80
+
81
+ userCache.set(pkg.name, {buildHash: pkg.buildHash, files});
82
+ console.log(`package-agents: extracted ${files.length} agent file(s) from ${pkg.name}`);
83
+ }
84
+
85
+ export async function syncPackages(userDir: string, packageName?: string): Promise<void> {
86
+ const wsPackages = await getWorkspacePackages();
87
+ if (packageName && wsPackages.has(packageName.toLowerCase())) {
88
+ console.log(`package-agents: skipping workspace package ${packageName}`);
89
+ return;
90
+ }
91
+
92
+ const packages = await request<PackageInfo[]>('GET', '/packages/published/current');
93
+ if (!Array.isArray(packages) || !packages.length) {
94
+ console.log('package-agents: no published packages found');
95
+ return;
96
+ }
97
+
98
+ const userId = path.basename(userDir);
99
+ setInstalledPackages(userId, packages);
100
+
101
+ let userCache = cache.get(userId);
102
+ if (!userCache) {
103
+ userCache = new Map();
104
+ cache.set(userId, userCache);
105
+ }
106
+
107
+ const agentsDir = path.join(userDir, 'agents');
108
+ const installed = new Set(packages.map((p) => p.name));
109
+
110
+ // Drop files + cache entries for packages no longer installed.
111
+ let orphans = 0;
112
+ for (const name of [...userCache.keys()]) {
113
+ if (!installed.has(name)) {
114
+ for (const f of userCache.get(name)!.files)
115
+ await fs.rm(path.join(agentsDir, f), {force: true});
116
+ userCache.delete(name);
117
+ orphans++;
118
+ }
119
+ }
120
+ if (orphans)
121
+ console.log(`package-agents: removed ${orphans} orphan package(s)`);
122
+
123
+ if (packageName) {
124
+ const pkg = packages.find((p) => p.name === packageName);
125
+ if (!pkg) {
126
+ console.log(`package-agents: package "${packageName}" not found among published`);
127
+ return;
128
+ }
129
+ try {
130
+ await syncSinglePackage(userDir, pkg, userCache);
131
+ } catch (e: any) {
132
+ console.warn(`package-agents: failed to sync ${pkg.name}: ${e.message}`);
133
+ }
134
+ return;
135
+ }
136
+
137
+ const toSync = packages.filter((pkg) => !wsPackages.has(pkg.name.toLowerCase()));
138
+ console.log(`package-agents: syncing ${toSync.length} published package(s), ` +
139
+ `skipping ${packages.length - toSync.length} workspace package(s)`);
140
+ for (let i = 0; i < toSync.length; i += SYNC_CONCURRENCY) {
141
+ await Promise.all(toSync.slice(i, i + SYNC_CONCURRENCY).map((pkg) =>
142
+ syncSinglePackage(userDir, pkg, userCache).catch((e: any) =>
143
+ console.warn(`package-agents: failed to sync ${pkg.name}: ${e.message}`))));
144
+ }
145
+ }
@@ -0,0 +1,87 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import {request, downloadFile} from '../shared-api-client';
4
+ import type {ConnectionInfo} from './orchestrator';
5
+ import {connectorPath, collectFiles} from './orchestrator';
6
+
7
+ const SHARED_AGENTS_CONN_NAME = 'MyFilesAgents';
8
+
9
+ // Per-user shared files cache: "connId/filePath" → updatedOn timestamp.
10
+ const sharedCache = new Map<string, Map<string, string>>();
11
+
12
+ // Discovers shared "Home/agents" connections and syncs their files.
13
+ // Skips the user's own Home connection (already synced separately).
14
+ // Files are stored as agents/shared-{connId}-{flatPath} to avoid collisions.
15
+ export async function syncSharedConnections(userDir: string, homeConnId: string | null): Promise<void> {
16
+ console.log('shared-connections: searching for shared agents folders...');
17
+ const connections = await request<ConnectionInfo[]>(
18
+ 'GET', '/public/v1/connections?text=agents',
19
+ );
20
+ console.log('shared-connections: API returned', (connections ?? []).map((c) => ({id: c.id, name: c.name})));
21
+ const shared = (connections ?? []).filter(
22
+ (c) => c.name === SHARED_AGENTS_CONN_NAME && c.id !== homeConnId,
23
+ );
24
+ if (!shared.length) {
25
+ console.log('shared-connections: no shared agents folders found');
26
+ return;
27
+ }
28
+ console.log(`shared-connections: found ${shared.length} shared agents folder(s)`);
29
+
30
+ const userId = path.basename(userDir);
31
+ if (!sharedCache.has(userId))
32
+ sharedCache.set(userId, new Map());
33
+ const cached = sharedCache.get(userId)!;
34
+
35
+ const agentsDir = path.join(userDir, 'agents');
36
+ const activeKeys = new Set<string>();
37
+
38
+ for (const conn of shared) {
39
+ const prefix = `shared-${conn.id}-`;
40
+ console.log(`shared-connections: syncing ${conn.id}`);
41
+
42
+ // The shared connection root IS the agents folder, so list from root
43
+ const remoteFiles = await collectFiles(conn.id, '');
44
+ if (!remoteFiles.length) {
45
+ console.log(`shared-connections: no files in ${conn.id}`);
46
+ continue;
47
+ }
48
+
49
+ const cPath = connectorPath(conn);
50
+ for (const remote of remoteFiles) {
51
+ const cacheKey = `${conn.id}/${remote.path}`;
52
+ activeKeys.add(cacheKey);
53
+ if (cached.get(cacheKey) === remote.updatedOn)
54
+ continue;
55
+
56
+ const label = cached.has(cacheKey) ? 'updated' : 'new';
57
+ console.log(`shared-connections: downloading ${label} file ${cacheKey}`);
58
+ try {
59
+ const content = await downloadFile(cPath, remote.path) as string;
60
+ const fileName = remote.path.replace(/\//g, '-');
61
+ const dest = path.join(agentsDir, `${prefix}${fileName}`);
62
+ await fs.writeFile(dest, content);
63
+ } catch (e: any) {
64
+ console.warn(`shared-connections: failed to download ${cacheKey}:`, e.message);
65
+ }
66
+ // Record the version seen even on failure: a file that can't be downloaded
67
+ // (e.g. invalid JSON) must not re-download every poll — retry only when its
68
+ // updatedOn changes.
69
+ cached.set(cacheKey, remote.updatedOn);
70
+ }
71
+ }
72
+
73
+ // Clean up files from connections that are no longer shared
74
+ for (const [key] of cached) {
75
+ if (!activeKeys.has(key)) {
76
+ const slashIdx = key.indexOf('/');
77
+ const connId = key.substring(0, slashIdx);
78
+ const filePath = key.substring(slashIdx + 1).replace(/\//g, '-');
79
+ const localFile = path.join(agentsDir, `shared-${connId}-${filePath}`);
80
+ try {
81
+ await fs.rm(localFile, {force: true});
82
+ console.log(`shared-connections: removed stale file ${localFile}`);
83
+ } catch { /* ignore */ }
84
+ cached.delete(key);
85
+ }
86
+ }
87
+ }
@@ -0,0 +1,68 @@
1
+ import {execFile} from 'node:child_process';
2
+ import * as path from 'node:path';
3
+ import {promisify} from 'node:util';
4
+ import {WORKSPACE} from '../constants';
5
+ import {buildHelpIndex} from '../help-index';
6
+
7
+ const exec = promisify(execFile);
8
+ const SYNC_INTERVAL_MS = 30 * 60 * 1000;
9
+ const HELP_WORKSPACE = path.join(WORKSPACE, 'help');
10
+
11
+ let activeCount = 0;
12
+ let syncing = false;
13
+ let resolveIdle: (() => void) | null = null;
14
+ let allQueriesIdle: Promise<void> = Promise.resolve();
15
+
16
+ export function markQueryStart(): void {
17
+ if (activeCount === 0)
18
+ allQueriesIdle = new Promise((r) => (resolveIdle = r));
19
+ activeCount++;
20
+ }
21
+
22
+ export function markQueryEnd(): void {
23
+ activeCount--;
24
+ if (activeCount === 0 && resolveIdle) {
25
+ resolveIdle();
26
+ resolveIdle = null;
27
+ }
28
+ }
29
+
30
+ async function syncRepo(dir: string): Promise<boolean> {
31
+ const oldSha = (await exec('git', ['-C', dir, 'rev-parse', 'HEAD'])).stdout.trim();
32
+ await exec('git', ['-C', dir, 'fetch', '--depth=1', 'origin', 'master']);
33
+ await exec('git', ['-C', dir, 'reset', '--hard', 'FETCH_HEAD']);
34
+ const newSha = (await exec('git', ['-C', dir, 'rev-parse', 'HEAD'])).stdout.trim();
35
+ if (oldSha === newSha)
36
+ return false;
37
+ console.log(`workspace: synced ${path.basename(dir)} ${oldSha.slice(0, 7)} → ${newSha.slice(0, 7)}`);
38
+ return true;
39
+ }
40
+
41
+ async function syncWorkspace(): Promise<void> {
42
+ if (syncing)
43
+ return;
44
+ syncing = true;
45
+ try {
46
+ await allQueriesIdle;
47
+ const publicChanged = await syncRepo(WORKSPACE);
48
+ const helpChanged = await syncRepo(HELP_WORKSPACE);
49
+ if (!publicChanged && !helpChanged) {
50
+ console.log('workspace: already up to date');
51
+ return;
52
+ }
53
+
54
+ try {
55
+ buildHelpIndex(WORKSPACE);
56
+ } catch (e: any) {
57
+ console.warn('help-index: rebuild failed:', e.message);
58
+ }
59
+ } catch (e: any) {
60
+ console.warn('workspace: sync failed:', e.message);
61
+ } finally {
62
+ syncing = false;
63
+ }
64
+ }
65
+
66
+ export function startWorkspaceSync(): void {
67
+ setInterval(syncWorkspace, SYNC_INTERVAL_MS);
68
+ }
@@ -0,0 +1,124 @@
1
+ /** One record per queued Grokky:aiChatTurnTask call admitting one chat turn; the queue carries
2
+ * only this admission, the turn streams over the browser WebSocket. Fail-open: a turn on a stand
3
+ * with no live workers is delayed by CLAIM_WAIT_MS, never blocked — but while workers are seen
4
+ * polling, an unclaimed task means the queue is busy, not broken, and the turn keeps waiting. */
5
+
6
+ export interface TaskEnd {status: 'ended' | 'released'}
7
+
8
+ interface Task {
9
+ sessionId: string;
10
+ claimed: boolean;
11
+ end?: TaskEnd;
12
+ claimWaiters: ((claimed: boolean) => void)[];
13
+ endWaiters: ((end: TaskEnd) => void)[];
14
+ deleteTimer?: NodeJS.Timeout;
15
+ }
16
+
17
+ // Backstop for a task whose turn never arrives (worker claimed, browser send failed).
18
+ const ORPHAN_TTL_MS = 30 * 60_000;
19
+ // How long an ended task lingers so a late worker poll still sees the terminal status.
20
+ const END_LINGER_MS = 5 * 60_000;
21
+ // One long-poll leg; the worker re-polls on {status: 'running'}. Kept well under proxy timeouts.
22
+ const CLAIM_POLL_MS = 25_000;
23
+ const CLAIM_WAIT_MS = 60_000;
24
+ // Any /task/claim poll this recent proves the worker pool is alive (a slot-holding worker
25
+ // re-polls every CLAIM_POLL_MS, so a busy queue refreshes this continuously).
26
+ const WORKER_LIVE_MS = 90_000;
27
+ // Bounds a wait whose workers died mid-queue; matches the worker's own HOLD_CAP_MS.
28
+ const CLAIM_WAIT_CAP_MS = 30 * 60_000;
29
+
30
+ let lastWorkerPollAt = 0;
31
+
32
+ const tasks = new Map<string, Task>();
33
+
34
+ function armDelete(taskId: string, t: Task, ms: number): void {
35
+ clearTimeout(t.deleteTimer);
36
+ t.deleteTimer = setTimeout(() => tasks.delete(taskId), ms);
37
+ t.deleteTimer.unref?.();
38
+ }
39
+
40
+ function getOrCreate(taskId: string, sessionId: string): Task {
41
+ let t = tasks.get(taskId);
42
+ if (!t) {
43
+ t = {sessionId, claimed: false, claimWaiters: [], endWaiters: []};
44
+ tasks.set(taskId, t);
45
+ armDelete(taskId, t, ORPHAN_TTL_MS);
46
+ }
47
+ return t;
48
+ }
49
+
50
+ /** One worker long-poll leg: claim (idempotent), then wait up to CLAIM_POLL_MS for the turn to end;
51
+ * {status: 'running'} means re-poll. */
52
+ export function claimTask(taskId: string, sessionId: string): Promise<TaskEnd | {status: 'running'}> {
53
+ lastWorkerPollAt = Date.now();
54
+ const t = getOrCreate(taskId, sessionId);
55
+ if (!t.claimed) {
56
+ t.claimed = true;
57
+ t.claimWaiters.splice(0).forEach((w) => w(true));
58
+ }
59
+ if (t.end)
60
+ return Promise.resolve(t.end);
61
+ return new Promise((resolve) => {
62
+ const onEnd = (end: TaskEnd) => {
63
+ clearTimeout(timer);
64
+ resolve(end);
65
+ };
66
+ const timer = setTimeout(() => {
67
+ const i = t.endWaiters.indexOf(onEnd);
68
+ if (i >= 0)
69
+ t.endWaiters.splice(i, 1);
70
+ resolve({status: 'running'});
71
+ }, CLAIM_POLL_MS);
72
+ t.endWaiters.push(onEnd);
73
+ });
74
+ }
75
+
76
+ /** Turn side: hold until the worker claims the task; false on fail-open timeout or abort. */
77
+ export function waitForClaim(taskId: string, sessionId: string, signal: AbortSignal): Promise<boolean> {
78
+ const t = getOrCreate(taskId, sessionId);
79
+ // A turn may outlive the orphan backstop; endTask (runTurn's finally) is the terminal now.
80
+ clearTimeout(t.deleteTimer);
81
+ if (t.claimed || signal.aborted)
82
+ return Promise.resolve(t.claimed);
83
+ const startedAt = Date.now();
84
+ return new Promise((resolve) => {
85
+ let timer: NodeJS.Timeout;
86
+ const done = (claimed: boolean) => {
87
+ clearTimeout(timer);
88
+ resolve(claimed);
89
+ };
90
+ const arm = () => {
91
+ timer = setTimeout(() => {
92
+ if (Date.now() - lastWorkerPollAt < WORKER_LIVE_MS && Date.now() - startedAt < CLAIM_WAIT_CAP_MS)
93
+ arm();
94
+ else
95
+ done(false);
96
+ }, CLAIM_WAIT_MS);
97
+ };
98
+ arm();
99
+ t.claimWaiters.push(done);
100
+ signal.addEventListener('abort', () => done(false), {once: true});
101
+ });
102
+ }
103
+
104
+ /** Terminal for every turn path — called from runTurn's finally. Idempotent. */
105
+ export function endTask(taskId: string): void {
106
+ const t = tasks.get(taskId);
107
+ if (!t || t.end)
108
+ return;
109
+ t.end = {status: 'ended'};
110
+ armDelete(taskId, t, END_LINGER_MS);
111
+ t.endWaiters.splice(0).forEach((w) => w(t.end!));
112
+ }
113
+
114
+ /** Platform-side cancel (task revoked): returns the sessionId whose turn should be aborted, if still live. */
115
+ export function releaseTask(taskId: string): string | null {
116
+ const t = tasks.get(taskId);
117
+ if (!t || t.end)
118
+ return null;
119
+ t.end = {status: 'released'};
120
+ armDelete(taskId, t, END_LINGER_MS);
121
+ t.endWaiters.splice(0).forEach((w) => w(t.end!));
122
+ t.claimWaiters.splice(0).forEach((w) => w(false));
123
+ return t.sessionId;
124
+ }