@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
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import type {AbortMessage, AgentEvent, InputResponseMessage, UserMessage, TurnMetrics} from './types';
|
|
3
|
+
import {raceIdle, IDLE} from './watchdog';
|
|
4
|
+
import {emit, emitFiltered, flushFenceState, clearFenceState,
|
|
5
|
+
isRevising, beginRevision, endRevision} from './stream-filter';
|
|
6
|
+
import type {WsSender} from './stream-filter';
|
|
7
|
+
import {syncUserFiles} from './sync/orchestrator';
|
|
8
|
+
import {userDirs} from './user/user-dir';
|
|
9
|
+
import {markQueryStart, markQueryEnd} from './sync/workspace';
|
|
10
|
+
import {Verifier} from './verify';
|
|
11
|
+
import {GroundingGate, isSmallTalk} from './grounding';
|
|
12
|
+
import {buildSystemPrompt} from './prompts';
|
|
13
|
+
import {WORKSPACE, apiUrlFromMcpUrl, rewriteForDocker} from './constants';
|
|
14
|
+
import {waitForClaim, endTask} from './tasks';
|
|
15
|
+
import {runTurn as runAgentTurn} from './agent/turn';
|
|
16
|
+
import {hasSession, parkSession} from './agent/pool';
|
|
17
|
+
import type {ProviderCredentials} from './credentials';
|
|
18
|
+
|
|
19
|
+
// Longest a turn may emit nothing before it is treated as wedged. Bounds silence between events,
|
|
20
|
+
// not total turn length.
|
|
21
|
+
const TURN_IDLE_TIMEOUT_MS = 90000;
|
|
22
|
+
|
|
23
|
+
// Visible streamed text of the in-flight turn, per session — the grounding gate reads it at Stop
|
|
24
|
+
// to decide whether the answer makes platform how-to claims (grounding.ts makesPlatformClaims).
|
|
25
|
+
const turnText = new Map<string, string>();
|
|
26
|
+
|
|
27
|
+
const TURN_LIMITS = {
|
|
28
|
+
full: {maxTurns: 100, maxBudgetUsd: 2.5},
|
|
29
|
+
bash: {maxTurns: 10, maxBudgetUsd: 0.25},
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const NO_REVISION_RE = /^`?NO_REVISION`?\.?$/;
|
|
33
|
+
|
|
34
|
+
function forwardEvent(ws: WsSender, sid: string, event: AgentEvent, verifier?: Verifier, metrics?: TurnMetrics): void {
|
|
35
|
+
if (event.type === 'text') {
|
|
36
|
+
if (!isRevising(sid))
|
|
37
|
+
turnText.set(sid, (turnText.get(sid) ?? '') + event.text);
|
|
38
|
+
return emitFiltered(ws, sid, event.text);
|
|
39
|
+
}
|
|
40
|
+
if (event.type === 'tool_activity')
|
|
41
|
+
return emit(ws, {type: 'tool_activity', sessionId: sid, name: event.name, summary: event.summary});
|
|
42
|
+
if (event.type === 'activity' || event.type === 'usage')
|
|
43
|
+
return;
|
|
44
|
+
const revising = endRevision(sid);
|
|
45
|
+
flushFenceState(ws, sid);
|
|
46
|
+
switch (event.type) {
|
|
47
|
+
case 'result': {
|
|
48
|
+
const noRevision = revising && NO_REVISION_RE.test(event.text.trim());
|
|
49
|
+
return emit(ws, {
|
|
50
|
+
type: 'final', sessionId: sid, content: noRevision ? '' : event.text,
|
|
51
|
+
...(revising ? {revision: noRevision ? 'kept' as const : 'replaced' as const} : {}),
|
|
52
|
+
...(event.structuredOutput !== undefined ? {structured_output: event.structuredOutput} : {}),
|
|
53
|
+
...(verifier?.exhausted ? {unverified: true} : {}),
|
|
54
|
+
metrics: event.metrics,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
case 'limit':
|
|
58
|
+
return emit(ws, {type: 'error', sessionId: sid,
|
|
59
|
+
message: `This request hit its ${event.kind === 'turns' ? 'turn' : 'cost'} limit and was stopped. ` +
|
|
60
|
+
'Try a narrower request.', metrics});
|
|
61
|
+
case 'session_reset':
|
|
62
|
+
return emit(ws, {type: 'session_reset', sessionId: sid});
|
|
63
|
+
case 'error':
|
|
64
|
+
return emit(ws, {type: 'error', sessionId: sid, message: event.message, metrics});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface ActiveQuery {
|
|
69
|
+
abortController: AbortController;
|
|
70
|
+
/** The connection that sent the turn; only it can stop the turn (one chat can be open in several tabs). */
|
|
71
|
+
ws: WsSender;
|
|
72
|
+
// requestId → resolver, so parallel tool calls each await their own browser reply.
|
|
73
|
+
pendingInputs: Map<string, (value: unknown) => void>;
|
|
74
|
+
/** The turn's usage so far, reported when it ends without a result of its own. */
|
|
75
|
+
metrics?: TurnMetrics;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Round-trips a tool call to the browser: emits input_request, resolves on the matching
|
|
79
|
+
// input_response. The requestId keeps parallel calls from crossing wires; rejects on abort.
|
|
80
|
+
const STOPPED = 'The user stopped this request.';
|
|
81
|
+
const DISCONNECTED = 'The browser connection dropped before this call reported back. Its code may still be ' +
|
|
82
|
+
'running, or may have finished, in the user\'s tab: check the current state before running it again.';
|
|
83
|
+
|
|
84
|
+
function awaitBrowserInput(
|
|
85
|
+
sid: string, active: ActiveQuery, toolName: string, input: unknown, timeoutMs: number,
|
|
86
|
+
): Promise<unknown> {
|
|
87
|
+
if (active.abortController.signal.aborted)
|
|
88
|
+
return Promise.reject(active.abortController.signal.reason);
|
|
89
|
+
const requestId = randomUUID();
|
|
90
|
+
emit(active.ws, {type: 'input_request', sessionId: sid, requestId, toolName, input});
|
|
91
|
+
return new Promise((resolve, reject) => {
|
|
92
|
+
const timer = setTimeout(() => {
|
|
93
|
+
if (active.pendingInputs.delete(requestId))
|
|
94
|
+
reject(new Error(`no browser response for ${toolName} after ${timeoutMs / 1000}s`));
|
|
95
|
+
}, timeoutMs);
|
|
96
|
+
active.pendingInputs.set(requestId, (value) => {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
resolve(value);
|
|
99
|
+
});
|
|
100
|
+
active.abortController.signal.addEventListener('abort', () => {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
if (active.pendingInputs.delete(requestId))
|
|
103
|
+
reject(active.abortController.signal.reason);
|
|
104
|
+
}, {once: true});
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const activeQueries = new Map<string, ActiveQuery>();
|
|
109
|
+
|
|
110
|
+
function registerActiveQuery(sid: string, q: ActiveQuery): void {
|
|
111
|
+
activeQueries.set(sid, q);
|
|
112
|
+
markQueryStart();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function unregisterActiveQuery(sid: string, q?: ActiveQuery): void {
|
|
116
|
+
if (q && activeQueries.get(sid) !== q)
|
|
117
|
+
return;
|
|
118
|
+
activeQueries.delete(sid);
|
|
119
|
+
markQueryEnd();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function handleInputResponse(ws: WsSender, data: InputResponseMessage): void {
|
|
123
|
+
const active = activeQueries.get(data.sessionId);
|
|
124
|
+
if (!active)
|
|
125
|
+
return;
|
|
126
|
+
// Correlate by requestId; fall back to the sole pending request for older clients that omit it.
|
|
127
|
+
const id = data.requestId ?? (active.pendingInputs.size === 1 ? active.pendingInputs.keys().next().value : undefined);
|
|
128
|
+
const resolve = id !== undefined ? active.pendingInputs.get(id) : undefined;
|
|
129
|
+
if (!resolve)
|
|
130
|
+
return;
|
|
131
|
+
active.pendingInputs.delete(id!);
|
|
132
|
+
resolve(data.value);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const QUEUED_HEARTBEAT_MS = 60_000;
|
|
136
|
+
|
|
137
|
+
const sessionChains = new Map<string, Promise<void>>();
|
|
138
|
+
|
|
139
|
+
export async function handleMessage(ws: WsSender, data: UserMessage,
|
|
140
|
+
credentials: Promise<ProviderCredentials>): Promise<void> {
|
|
141
|
+
const sid = data.sessionId ?? '';
|
|
142
|
+
const message = data.message ?? '';
|
|
143
|
+
const images = data.images;
|
|
144
|
+
if (!message && !images?.length) {
|
|
145
|
+
if (data.taskId)
|
|
146
|
+
endTask(data.taskId);
|
|
147
|
+
return emit(ws, {type: 'error', sessionId: sid, message: 'Empty message'});
|
|
148
|
+
}
|
|
149
|
+
const prev = sessionChains.get(sid);
|
|
150
|
+
let release!: () => void;
|
|
151
|
+
const turn = new Promise<void>((resolve) => { release = resolve; });
|
|
152
|
+
const tail = prev ? prev.then(() => turn) : turn;
|
|
153
|
+
sessionChains.set(sid, tail);
|
|
154
|
+
try {
|
|
155
|
+
if (prev) {
|
|
156
|
+
emit(ws, {type: 'queued', sessionId: sid});
|
|
157
|
+
const heartbeat = setInterval(() => emit(ws, {type: 'queued', sessionId: sid}), QUEUED_HEARTBEAT_MS);
|
|
158
|
+
try {
|
|
159
|
+
await prev;
|
|
160
|
+
} finally {
|
|
161
|
+
clearInterval(heartbeat);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
await runTurn(ws, data, sid, message, credentials);
|
|
165
|
+
} finally {
|
|
166
|
+
release();
|
|
167
|
+
if (sessionChains.get(sid) === tail)
|
|
168
|
+
sessionChains.delete(sid);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function runTurn(ws: WsSender, data: UserMessage, sid: string, message: string,
|
|
173
|
+
credentials: Promise<ProviderCredentials>): Promise<void> {
|
|
174
|
+
// Registered before anything is awaited, so an abort that arrives at any point reaches this turn.
|
|
175
|
+
const abortController = new AbortController();
|
|
176
|
+
const active: ActiveQuery = {abortController, ws, pendingInputs: new Map()};
|
|
177
|
+
registerActiveQuery(sid, active);
|
|
178
|
+
|
|
179
|
+
let verifier: Verifier | undefined;
|
|
180
|
+
let groundingGate: GroundingGate | undefined;
|
|
181
|
+
try {
|
|
182
|
+
// Reset at once: the browser resends the turn with its transcript, and that one waits for admission.
|
|
183
|
+
if (data.resumeExpected && !hasSession(sid))
|
|
184
|
+
return emit(ws, {type: 'session_reset', sessionId: sid});
|
|
185
|
+
const mcpUrl = rewriteForDocker(data.mcpServerUrl || '');
|
|
186
|
+
const turnCredentials = await credentials;
|
|
187
|
+
// Admission: wait for the celery claim (when the queued route is deployed) — the
|
|
188
|
+
// queue container's concurrency limit is the only cap on concurrent turns.
|
|
189
|
+
if (data.taskId) {
|
|
190
|
+
emit(ws, {type: 'queued', sessionId: sid});
|
|
191
|
+
const heartbeat = setInterval(() => emit(ws, {type: 'queued', sessionId: sid}), QUEUED_HEARTBEAT_MS);
|
|
192
|
+
try {
|
|
193
|
+
if (!await waitForClaim(data.taskId, sid, abortController.signal) && !abortController.signal.aborted)
|
|
194
|
+
console.warn(`task[${sid}]: no claim for ${data.taskId} — failing open`);
|
|
195
|
+
} finally {
|
|
196
|
+
clearInterval(heartbeat);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (abortController.signal.aborted)
|
|
200
|
+
return;
|
|
201
|
+
|
|
202
|
+
const apiUrl = apiUrlFromMcpUrl(mcpUrl);
|
|
203
|
+
const userDir = data.apiKey ? await userDirs.ensureDir(data.apiKey, apiUrl) : undefined;
|
|
204
|
+
|
|
205
|
+
if (apiUrl && data.apiKey) {
|
|
206
|
+
// First sync per user blocks so workspace/ exists for this turn; warm turns return
|
|
207
|
+
// straight from disk (see orchestrator.ts).
|
|
208
|
+
await syncUserFiles(apiUrl, data.apiKey).catch((e: any) =>
|
|
209
|
+
console.warn('handleMessage: failed to sync user files:', e.message));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const mode = data.systemPromptMode === 'bash' || data.systemPromptMode === 'none' ||
|
|
213
|
+
data.systemPromptMode === 'search' ? data.systemPromptMode : 'datagrok';
|
|
214
|
+
const fullPromptTurn = mode === 'datagrok' || mode === 'search';
|
|
215
|
+
// The visible answer stays until `final` says whether the hidden revision replaces it.
|
|
216
|
+
const onGateBlock = () => {
|
|
217
|
+
if (!isRevising(sid)) {
|
|
218
|
+
flushFenceState(ws, sid);
|
|
219
|
+
beginRevision(sid);
|
|
220
|
+
emit(ws, {type: 'revision_start', sessionId: sid});
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const gates = data.gates ?? {};
|
|
224
|
+
verifier = mode === 'datagrok' && gates.verify !== false ? new Verifier(onGateBlock) : undefined;
|
|
225
|
+
turnText.delete(sid); // fresh answer buffer — the gate must judge THIS turn's text only
|
|
226
|
+
groundingGate = fullPromptTurn && gates.grounding !== false && !data.outputSchema &&
|
|
227
|
+
!isSmallTalk(data.message ?? '') ?
|
|
228
|
+
new GroundingGate(onGateBlock, () => turnText.get(sid) ?? '') : undefined;
|
|
229
|
+
|
|
230
|
+
const it = runAgentTurn({
|
|
231
|
+
sessionKey: sid, text: message, images: data.images, systemPrompt: buildSystemPrompt(mode),
|
|
232
|
+
effort: fullPromptTurn ? 'high' : undefined,
|
|
233
|
+
cwd: userDir || WORKSPACE, userDir, resumeExpected: data.resumeExpected,
|
|
234
|
+
outputSchema: data.outputSchema, clientTools: data.clientTools, browserTools: mode !== 'search',
|
|
235
|
+
datagrokMcp: mcpUrl ? {url: mcpUrl, headers: {
|
|
236
|
+
...(data.apiKey ? {'x-user-api-key': data.apiKey, 'Authorization': data.apiKey} : {}),
|
|
237
|
+
...(apiUrl ? {'x-datagrok-api-url': apiUrl} : {}),
|
|
238
|
+
}} : undefined,
|
|
239
|
+
limits: TURN_LIMITS[fullPromptTurn ? 'full' : 'bash'],
|
|
240
|
+
gates: [verifier, groundingGate].filter((g) => g !== undefined),
|
|
241
|
+
awaitBrowser: (toolName, input, timeoutMs) => awaitBrowserInput(sid, active, toolName, input, timeoutMs),
|
|
242
|
+
showInBrowser: (toolName, input) =>
|
|
243
|
+
emit(active.ws, {type: 'input_request', sessionId: sid, requestId: randomUUID(), toolName, input}),
|
|
244
|
+
signal: abortController.signal,
|
|
245
|
+
credentials: turnCredentials,
|
|
246
|
+
});
|
|
247
|
+
// Each event is raced against the idle timeout, so a turn that goes silent is bounded (see
|
|
248
|
+
// watchdog.ts): a wedged agent emits nothing at all, which a plain await would wait on forever.
|
|
249
|
+
let pendingStep: Promise<IteratorResult<AgentEvent, undefined>> | null = null;
|
|
250
|
+
for (;;) {
|
|
251
|
+
pendingStep = pendingStep ?? it.next();
|
|
252
|
+
const step = await raceIdle(pendingStep, TURN_IDLE_TIMEOUT_MS);
|
|
253
|
+
if (step === IDLE) {
|
|
254
|
+
// Work inside the agent sends activity; a browser round-trip (a tool running in the tab, a question the user
|
|
255
|
+
// has not answered) is silent but carries its own timeout.
|
|
256
|
+
if (active.pendingInputs.size > 0)
|
|
257
|
+
continue;
|
|
258
|
+
console.warn(`watchdog[${sid}]: no agent event for ${TURN_IDLE_TIMEOUT_MS / 1000}s — killing turn`);
|
|
259
|
+
emit(ws, {type: 'error', sessionId: sid,
|
|
260
|
+
message: 'The assistant stopped responding and the turn was cancelled. Please try again.',
|
|
261
|
+
metrics: active.metrics});
|
|
262
|
+
abortController.abort();
|
|
263
|
+
parkSession(sid, `turn ${sid} went silent`);
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
pendingStep = null;
|
|
267
|
+
if (step.done || abortController.signal.aborted)
|
|
268
|
+
break;
|
|
269
|
+
// A command's answer is its output, the final message: models remark before the tool call despite the prompt.
|
|
270
|
+
if (mode === 'bash' && step.value.type === 'text')
|
|
271
|
+
continue;
|
|
272
|
+
if (step.value.type === 'usage')
|
|
273
|
+
active.metrics = step.value.metrics;
|
|
274
|
+
forwardEvent(ws, sid, step.value, verifier, active.metrics);
|
|
275
|
+
}
|
|
276
|
+
} catch (e: any) {
|
|
277
|
+
if (!abortController.signal.aborted)
|
|
278
|
+
emit(ws, {type: 'error', sessionId: sid, message: String(e.message || e), metrics: active.metrics});
|
|
279
|
+
} finally {
|
|
280
|
+
// Every terminal path — final, error, abort, disconnect, watchdog kill — ends the
|
|
281
|
+
// admission task here, so the celery slot can never outlive the turn it admitted.
|
|
282
|
+
if (data.taskId)
|
|
283
|
+
endTask(data.taskId);
|
|
284
|
+
if (verifier?.hadActions)
|
|
285
|
+
console.log(`verify[${sid}]: ${verifier.statsLine()}`);
|
|
286
|
+
if (groundingGate)
|
|
287
|
+
console.log(`grounding[${sid}]: ${groundingGate.summary()}`);
|
|
288
|
+
if (activeQueries.get(sid) === active) {
|
|
289
|
+
clearFenceState(sid);
|
|
290
|
+
endRevision(sid);
|
|
291
|
+
turnText.delete(sid);
|
|
292
|
+
}
|
|
293
|
+
unregisterActiveQuery(sid, active);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function abortSessionQuery(sid: string, reason: string, ws?: WsSender): boolean {
|
|
298
|
+
const active = activeQueries.get(sid);
|
|
299
|
+
if (!active)
|
|
300
|
+
return false;
|
|
301
|
+
active.abortController.abort(new Error(reason));
|
|
302
|
+
unregisterActiveQuery(sid, active);
|
|
303
|
+
endRevision(sid);
|
|
304
|
+
turnText.delete(sid);
|
|
305
|
+
if (ws)
|
|
306
|
+
flushFenceState(ws, sid);
|
|
307
|
+
else
|
|
308
|
+
clearFenceState(sid);
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function handleAbort(ws: WsSender, data: AbortMessage): void {
|
|
313
|
+
const active = activeQueries.get(data.sessionId);
|
|
314
|
+
if (active?.ws === ws && abortSessionQuery(data.sessionId, STOPPED, ws))
|
|
315
|
+
emit(ws, {type: 'aborted', sessionId: data.sessionId, metrics: active.metrics});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Stops the turns of these sessions that `ws` sent (all of them without `ws`: a revoked admission task). A dropped
|
|
319
|
+
* connection can never receive results, and a turn nobody waits for would hold the workspace sync. */
|
|
320
|
+
export function handleDisconnect(sessionIds: Iterable<string>, ws?: WsSender): void {
|
|
321
|
+
for (const sid of sessionIds) {
|
|
322
|
+
const active = activeQueries.get(sid);
|
|
323
|
+
if (!ws && active && abortSessionQuery(sid, STOPPED))
|
|
324
|
+
emit(active.ws, {type: 'aborted', sessionId: sid, metrics: active.metrics});
|
|
325
|
+
else if (ws && active?.ws === ws)
|
|
326
|
+
abortSessionQuery(sid, DISCONNECTED);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Duplicated in mcp-server/src/shared-api-client.ts — keep in sync.
|
|
2
|
+
// Can't be shared because each Docker container builds with its own context.
|
|
3
|
+
import {AsyncLocalStorage} from 'node:async_hooks';
|
|
4
|
+
|
|
5
|
+
interface RequestContext {
|
|
6
|
+
apiKey: string;
|
|
7
|
+
apiUrl: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const ctxStore = new AsyncLocalStorage<RequestContext>();
|
|
11
|
+
|
|
12
|
+
function _ctx(): RequestContext {
|
|
13
|
+
const ctx = ctxStore.getStore();
|
|
14
|
+
if (!ctx)
|
|
15
|
+
throw new Error('No request context — missing x-user-api-key / x-datagrok-api-url headers');
|
|
16
|
+
return ctx;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function runWithContext<T>(ctx: RequestContext, fn: () => T): T {
|
|
20
|
+
return ctxStore.run(ctx, fn);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Connection {
|
|
24
|
+
id: string;
|
|
25
|
+
name: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function toGrokPath(name: string): string {
|
|
29
|
+
return name.replace(/:/g, '.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function request<T = unknown>(
|
|
33
|
+
method: string, path: string, body?: unknown, headers?: Record<string, string>,
|
|
34
|
+
): Promise<T> {
|
|
35
|
+
const ctx = _ctx();
|
|
36
|
+
const url = `${ctx.apiUrl}/${path.replace(/^\//, '')}`;
|
|
37
|
+
const res = await fetch(url, {
|
|
38
|
+
method,
|
|
39
|
+
headers: {
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
'Authorization': ctx.apiKey,
|
|
42
|
+
...headers,
|
|
43
|
+
},
|
|
44
|
+
body: body === undefined ? undefined : (typeof body === 'string' ? body : JSON.stringify(body)),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (!res.ok) {
|
|
48
|
+
const text = await res.text();
|
|
49
|
+
throw new Error(`HTTP ${res.status}: ${text}`);
|
|
50
|
+
}
|
|
51
|
+
if (res.headers.has('api-error')) {
|
|
52
|
+
const text = await res.text();
|
|
53
|
+
throw new Error(`API error: ${text}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const ct = res.headers.get('content-type') ?? '';
|
|
57
|
+
if (ct.includes('application/json'))
|
|
58
|
+
return res.json();
|
|
59
|
+
return res.text() as T;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function requestBinary(
|
|
63
|
+
method: string, path: string,
|
|
64
|
+
): Promise<Buffer> {
|
|
65
|
+
const ctx = _ctx();
|
|
66
|
+
const url = `${ctx.apiUrl}/${path.replace(/^\//, '')}`;
|
|
67
|
+
const res = await fetch(url, {
|
|
68
|
+
method,
|
|
69
|
+
headers: {'Authorization': ctx.apiKey},
|
|
70
|
+
});
|
|
71
|
+
if (!res.ok) {
|
|
72
|
+
const text = await res.text();
|
|
73
|
+
throw new Error(`HTTP ${res.status}: ${text}`);
|
|
74
|
+
}
|
|
75
|
+
return Buffer.from(await res.arrayBuffer());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Lists the immediate children of a published-package folder (path MUST end with '/').
|
|
79
|
+
// Subdirectory names carry a trailing '/'. Returns null on 404 (folder absent).
|
|
80
|
+
export async function listPackageFolder(path: string): Promise<string[] | null> {
|
|
81
|
+
const ctx = _ctx();
|
|
82
|
+
const url = `${ctx.apiUrl}/${path.replace(/^\//, '')}`;
|
|
83
|
+
const res = await fetch(url, {method: 'GET', headers: {'Authorization': ctx.apiKey}});
|
|
84
|
+
if (res.status === 404)
|
|
85
|
+
return null;
|
|
86
|
+
if (!res.ok) {
|
|
87
|
+
const text = await res.text();
|
|
88
|
+
throw new Error(`HTTP ${res.status}: ${text}`);
|
|
89
|
+
}
|
|
90
|
+
return res.json() as Promise<string[]>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export async function listFiles(connector: string, path?: string): Promise<unknown[]> {
|
|
94
|
+
const searchName = connector.includes(':') ? connector.split(':').pop()! : connector;
|
|
95
|
+
const conns = await request<Connection[]>(
|
|
96
|
+
'GET', `/public/v1/connections?text=${encodeURIComponent(searchName)}`,
|
|
97
|
+
);
|
|
98
|
+
if (!conns.length)
|
|
99
|
+
throw new Error(`Connection "${connector}" not found`);
|
|
100
|
+
const filePath = path ? `${path.replace(/^\//, '')}/` : '';
|
|
101
|
+
return request('GET', `/connectors/connections/${conns[0].id}/files/${filePath}`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function downloadFile(connector: string, path: string): Promise<unknown> {
|
|
105
|
+
return request('GET', `/public/v1/files/${toGrokPath(connector)}/${path}`, undefined,
|
|
106
|
+
{'Accept': 'application/octet-stream'});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function uploadFile(connector: string, path: string, content: string): Promise<unknown> {
|
|
110
|
+
return request('POST', `/public/v1/files/${toGrokPath(connector)}/${path}`, content,
|
|
111
|
+
{'Content-Type': 'application/octet-stream'});
|
|
112
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type {OutgoingMessage} from './types';
|
|
2
|
+
|
|
3
|
+
export interface WsSender {
|
|
4
|
+
send(data: string): void;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function emit(ws: WsSender, msg: OutgoingMessage): void {
|
|
8
|
+
ws.send(JSON.stringify(msg));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function emitChunk(ws: WsSender, sid: string, content: string): void {
|
|
12
|
+
emit(ws, {type: 'chunk', sessionId: sid, content});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type FenceMode = 'prose' | 'other';
|
|
16
|
+
interface FenceState { mode: FenceMode; carry: string; lineInProgress: boolean; }
|
|
17
|
+
const fenceStates = new Map<string, FenceState>();
|
|
18
|
+
const FENCE_RE = /^```([\w-]*)\s*$/;
|
|
19
|
+
|
|
20
|
+
// Sessions whose turn is in a gate-demanded revision: the already-streamed answer stays visible in
|
|
21
|
+
// the browser, the revision text is NOT streamed, and the `result` decides kept vs replaced.
|
|
22
|
+
const revisingSids = new Set<string>();
|
|
23
|
+
|
|
24
|
+
export const isRevising = (sid: string): boolean => revisingSids.has(sid);
|
|
25
|
+
export const beginRevision = (sid: string): void => void revisingSids.add(sid);
|
|
26
|
+
/** Ends a revision, reporting whether one was in progress. */
|
|
27
|
+
export const endRevision = (sid: string): boolean => revisingSids.delete(sid);
|
|
28
|
+
export const clearFenceState = (sid: string): void => void fenceStates.delete(sid);
|
|
29
|
+
|
|
30
|
+
// Streams one model text delta. Holds only the partial trailing line when it could
|
|
31
|
+
// still become a fence marker (starts with `` ` `` at line start); everything else is emitted
|
|
32
|
+
// immediately under the current mode. Complete lines are batched per same-mode group so a
|
|
33
|
+
// 50-line delta yields ~3 emits, not 50.
|
|
34
|
+
export function emitFiltered(ws: WsSender, sid: string, text: string): void {
|
|
35
|
+
if (revisingSids.has(sid))
|
|
36
|
+
return;
|
|
37
|
+
const st = fenceStates.get(sid) ?? {mode: 'prose' as FenceMode, carry: '', lineInProgress: false};
|
|
38
|
+
fenceStates.set(sid, st);
|
|
39
|
+
|
|
40
|
+
const buf = st.carry + text;
|
|
41
|
+
st.carry = '';
|
|
42
|
+
const lastNl = buf.lastIndexOf('\n');
|
|
43
|
+
|
|
44
|
+
if (lastNl >= 0) {
|
|
45
|
+
const lines = buf.slice(0, lastNl).split('\n');
|
|
46
|
+
let groupStart = 0;
|
|
47
|
+
for (let i = 0; i < lines.length; i++) {
|
|
48
|
+
const couldBeFence = i > 0 || !st.lineInProgress;
|
|
49
|
+
const fence = couldBeFence ? FENCE_RE.exec(lines[i]) : null;
|
|
50
|
+
if (!fence) continue;
|
|
51
|
+
|
|
52
|
+
if (i > groupStart)
|
|
53
|
+
emitChunk(ws, sid, lines.slice(groupStart, i).join('\n') + '\n');
|
|
54
|
+
|
|
55
|
+
emitChunk(ws, sid, lines[i] + '\n');
|
|
56
|
+
st.mode = st.mode === 'prose' ? 'other' : 'prose';
|
|
57
|
+
groupStart = i + 1;
|
|
58
|
+
}
|
|
59
|
+
if (groupStart < lines.length)
|
|
60
|
+
emitChunk(ws, sid, lines.slice(groupStart).join('\n') + '\n');
|
|
61
|
+
st.lineInProgress = false;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const partial = lastNl < 0 ? buf : buf.slice(lastNl + 1);
|
|
65
|
+
if (partial.length === 0) return;
|
|
66
|
+
|
|
67
|
+
if (!st.lineInProgress && partial.startsWith('`'))
|
|
68
|
+
st.carry = partial;
|
|
69
|
+
else {
|
|
70
|
+
emitChunk(ws, sid, partial);
|
|
71
|
+
st.lineInProgress = true;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function flushFenceState(ws: WsSender, sid: string): void {
|
|
76
|
+
const st = fenceStates.get(sid);
|
|
77
|
+
if (st?.carry)
|
|
78
|
+
emitChunk(ws, sid, st.carry);
|
|
79
|
+
fenceStates.delete(sid);
|
|
80
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
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
|
+
// Per-user file metadata cache: relative path → updatedOn timestamp.
|
|
8
|
+
const userFileCache = new Map<string, Map<string, string>>();
|
|
9
|
+
|
|
10
|
+
export async function resolveHomeConnection(): Promise<{connId: string; connectorPath: string} | null> {
|
|
11
|
+
console.log('user-files: resolving Home connection...');
|
|
12
|
+
const conns = await request<ConnectionInfo[]>('GET', '/public/v1/connections?text=My%20files');
|
|
13
|
+
const home = conns.find((c) => c.name === 'Home');
|
|
14
|
+
if (!home) {
|
|
15
|
+
console.warn('user-files: Home connection not found among', conns.map((c) => c.name));
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
console.log(`user-files: resolved Home connection id=${home.id}`);
|
|
19
|
+
return {connId: home.id, connectorPath: connectorPath(home)};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Compares remote file timestamps against a local cache and only
|
|
23
|
+
// downloads files that are new or have changed. Removes local files that
|
|
24
|
+
// no longer exist on the remote side.
|
|
25
|
+
export async function syncHomeFiles(
|
|
26
|
+
userDir: string, connId: string, connPath: string,
|
|
27
|
+
): Promise<string[]> {
|
|
28
|
+
const userId = path.basename(userDir);
|
|
29
|
+
if (!userFileCache.has(userId))
|
|
30
|
+
userFileCache.set(userId, new Map());
|
|
31
|
+
const cached = userFileCache.get(userId)!;
|
|
32
|
+
|
|
33
|
+
const remoteFiles = await collectFiles(connId, 'agents');
|
|
34
|
+
console.log(`user-files: remote has ${remoteFiles.length} file(s) in agents/`);
|
|
35
|
+
|
|
36
|
+
const remoteSet = new Set<string>();
|
|
37
|
+
const downloaded: string[] = [];
|
|
38
|
+
|
|
39
|
+
for (const remote of remoteFiles) {
|
|
40
|
+
remoteSet.add(remote.path);
|
|
41
|
+
const cachedTs = cached.get(remote.path);
|
|
42
|
+
console.log(`user-files: checking ${remote.path} — remote ts=${remote.updatedOn || '<empty>'}, ` +
|
|
43
|
+
`cached ts=${cachedTs ?? 'none'}, match=${cachedTs === remote.updatedOn}`);
|
|
44
|
+
if (cachedTs === remote.updatedOn)
|
|
45
|
+
continue;
|
|
46
|
+
|
|
47
|
+
const label = cachedTs ? 'updated' : 'new';
|
|
48
|
+
console.log(`user-files: downloading ${label} file ${remote.path}`);
|
|
49
|
+
try {
|
|
50
|
+
const content = await downloadFile(connPath, remote.path) as string;
|
|
51
|
+
const dest = path.join(userDir, remote.path);
|
|
52
|
+
await fs.mkdir(path.dirname(dest), {recursive: true});
|
|
53
|
+
await fs.writeFile(dest, content);
|
|
54
|
+
cached.set(remote.path, remote.updatedOn);
|
|
55
|
+
downloaded.push(remote.path.replace(/^agents\//, ''));
|
|
56
|
+
} catch (e: any) {
|
|
57
|
+
console.warn(`user-files: failed to download ${remote.path}:`, e.message);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Remove local files that were deleted on the remote side
|
|
62
|
+
const agentsDir = path.join(userDir, 'agents');
|
|
63
|
+
try {
|
|
64
|
+
const localEntries = await fs.readdir(agentsDir, {recursive: true, withFileTypes: true});
|
|
65
|
+
for (const entry of localEntries) {
|
|
66
|
+
if (!entry.isFile())
|
|
67
|
+
continue;
|
|
68
|
+
const rel = path.relative(agentsDir, path.join(entry.parentPath, entry.name));
|
|
69
|
+
const remotePath = `agents/${rel}`;
|
|
70
|
+
// Only remove files that were synced from My files (not package files).
|
|
71
|
+
if (!remoteSet.has(remotePath) && cached.has(remotePath)) {
|
|
72
|
+
console.log(`user-files: removing deleted file ${remotePath}`);
|
|
73
|
+
await fs.rm(path.join(entry.parentPath, entry.name), {force: true});
|
|
74
|
+
cached.delete(remotePath);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} catch { /* agents dir may not exist yet */ }
|
|
78
|
+
|
|
79
|
+
return downloaded;
|
|
80
|
+
}
|