@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,411 @@
|
|
|
1
|
+
import {spawn} from 'node:child_process';
|
|
2
|
+
import type {ChildProcessWithoutNullStreams} from 'node:child_process';
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
import * as readline from 'node:readline';
|
|
7
|
+
import type {AgentCommand, AgentProcessEvent} from '../types';
|
|
8
|
+
import {AGENT_DIR, AGENT_PYTHON, HERMES_HOMES, PLUGIN_DIR} from '../constants';
|
|
9
|
+
import type {ProviderCredentials} from '../credentials';
|
|
10
|
+
import {IDLE, killTree, raceIdle, startOrphanReaper} from '../watchdog';
|
|
11
|
+
|
|
12
|
+
// One agent process (agent/grokky_agent) per Grokky session, each with its own HERMES_HOME and process group.
|
|
13
|
+
// An idle one holds about 250 MB RSS: the default 12 processes, spares included, fit the container's 8 GB.
|
|
14
|
+
const envNumber = (name: string, fallback: number) => process.env[name] ? Number(process.env[name]) : fallback;
|
|
15
|
+
const MAX_PROCESSES = envNumber('HERMES_MAX_PROCESSES', 12);
|
|
16
|
+
const IDLE_TTL_MS = envNumber('HERMES_IDLE_TTL_MS', 15 * 60_000);
|
|
17
|
+
const WARM_SPARES = Math.max(0, envNumber('HERMES_WARM_SPARES', 2));
|
|
18
|
+
const MAX_SESSIONS = envNumber('HERMES_MAX_SESSIONS', 200);
|
|
19
|
+
const COMPRESSION_THRESHOLD_TOKENS = envNumber('HERMES_COMPRESSION_THRESHOLD_TOKENS', 160_000);
|
|
20
|
+
const readyTimeoutMs = () => envNumber('HERMES_READY_TIMEOUT_MS', 30_000);
|
|
21
|
+
const PARKED_DIR = path.join(HERMES_HOMES, 'parked');
|
|
22
|
+
// Hermes' session store (sqlite, WAL); the rest of a home is rebuilt on reload.
|
|
23
|
+
const SESSION_STATE = /^state\.db(-wal|-shm)?$/;
|
|
24
|
+
const STDERR_TAIL_LINES = 40;
|
|
25
|
+
// Unexpected exits in a row after which a session's store is dropped: the chat then recovers from the transcript.
|
|
26
|
+
const MAX_CRASHES = 2;
|
|
27
|
+
|
|
28
|
+
// Agent output reaches the log and the browser: it loses the agent's own key and anything shaped like one.
|
|
29
|
+
const redact = (text: string, key?: string) => (key ? text.split(key).join('<redacted>') : text)
|
|
30
|
+
.replace(/\bsk-[\w.…-]+/g, 'sk-<redacted>');
|
|
31
|
+
|
|
32
|
+
export interface AgentProcess {
|
|
33
|
+
proc: ChildProcessWithoutNullStreams;
|
|
34
|
+
home: string;
|
|
35
|
+
/** What the agent was started with: it serves only turns of the same credentials. */
|
|
36
|
+
credentials: ProviderCredentials;
|
|
37
|
+
ready: Promise<void>;
|
|
38
|
+
/** `ready` has resolved: until then the process is neither idle nor evictable. */
|
|
39
|
+
started: boolean;
|
|
40
|
+
disposed: boolean;
|
|
41
|
+
sessionKey?: string;
|
|
42
|
+
/** The Hermes session the process holds; a parked session carries it to the process that reloads it. */
|
|
43
|
+
hermesSession?: string;
|
|
44
|
+
/** The parked session a reloading process has not opened yet; sent with each turn until the agent has. */
|
|
45
|
+
restore?: string;
|
|
46
|
+
turns: number;
|
|
47
|
+
turn: {events: (ev: AgentProcessEvent) => void; settled: Promise<void>} | null;
|
|
48
|
+
lastUsed: number;
|
|
49
|
+
stderrTail: string[];
|
|
50
|
+
/** The home is a stored session's and outlives this process (a reload that failed, or a process that died holding
|
|
51
|
+
* its session). */
|
|
52
|
+
keepHome?: boolean;
|
|
53
|
+
/** Unexpected exits of the session's processes since a turn last completed. */
|
|
54
|
+
crashes: number;
|
|
55
|
+
beforeForget?: () => void;
|
|
56
|
+
send(cmd: AgentCommand): void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface ParkedSession {
|
|
60
|
+
home: string;
|
|
61
|
+
hermesSession: string;
|
|
62
|
+
crashes?: number;
|
|
63
|
+
/** Resolves once the evicted process has exited and its session store is in `home`. */
|
|
64
|
+
stored: Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The stored history of a session is gone: the turn resets the chat and the browser replays it. */
|
|
68
|
+
export class SessionLost extends Error {}
|
|
69
|
+
|
|
70
|
+
const bySession = new Map<string, AgentProcess>();
|
|
71
|
+
const all = new Set<AgentProcess>();
|
|
72
|
+
const spares: AgentProcess[] = [];
|
|
73
|
+
const parked = new Map<string, ParkedSession>();
|
|
74
|
+
// Spares still starting; a session that finds no ready spare takes one of these over rather than paying for a
|
|
75
|
+
// second cold start next to it.
|
|
76
|
+
const starting: {proc: Promise<AgentProcess>; claimed: boolean; credentials: ProviderCredentials}[] = [];
|
|
77
|
+
// Most deployments share one set, so new spares use the credentials an agent last started with. Spares of other
|
|
78
|
+
// credentials stay until a session of theirs takes them or room is needed.
|
|
79
|
+
let spareCredentials: ProviderCredentials | undefined;
|
|
80
|
+
|
|
81
|
+
export const processForSession = (key: string) => bySession.get(key);
|
|
82
|
+
export const isParked = (key: string) => parked.has(key);
|
|
83
|
+
export const hasSession = (key: string) => holdsSession(bySession.get(key)) || parked.has(key);
|
|
84
|
+
// A process restoring a stored session holds it before its first turn has run.
|
|
85
|
+
const holdsSession = (p?: AgentProcess) => !!p && (p.turns > 0 || p.restore !== undefined);
|
|
86
|
+
export const hasExited = (p: AgentProcess) => p.proc.exitCode !== null || p.proc.signalCode !== null;
|
|
87
|
+
|
|
88
|
+
export function ownedPids(): Set<number> {
|
|
89
|
+
return new Set([...all].flatMap((p) => p.proc.pid ?? []));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function spawnProcess(credentials: ProviderCredentials, reload?: ParkedSession): Promise<AgentProcess> {
|
|
93
|
+
// Only a reload waits: a spare is in `all` the moment its spawn begins, which topUpSpares counts on.
|
|
94
|
+
if (reload)
|
|
95
|
+
await reload.stored;
|
|
96
|
+
if (reload && !fs.existsSync(reload.home))
|
|
97
|
+
throw new SessionLost(`the stored home ${reload.home} is gone`);
|
|
98
|
+
const spawnedAt = Date.now();
|
|
99
|
+
const home = reload?.home ?? path.join(HERMES_HOMES, randomUUID());
|
|
100
|
+
// Another session's agent (same uid) can write into a stored home; only the session store is kept.
|
|
101
|
+
for (const f of reload ? fs.readdirSync(home).filter((n) => !SESSION_STATE.test(n)) : [])
|
|
102
|
+
fs.rmSync(path.join(home, f), {recursive: true, force: true});
|
|
103
|
+
fs.mkdirSync(home, {recursive: true, mode: 0o700});
|
|
104
|
+
const proc = spawnAgent(home, !reload, credentials.values);
|
|
105
|
+
const tag = path.basename(home).slice(0, 8);
|
|
106
|
+
const p: AgentProcess = {
|
|
107
|
+
proc, home, credentials, ready: Promise.resolve(), started: false, disposed: false, turns: 0, turn: null,
|
|
108
|
+
lastUsed: Date.now(), stderrTail: [], restore: reload?.hermesSession, hermesSession: reload?.hermesSession,
|
|
109
|
+
crashes: reload?.crashes ?? 0,
|
|
110
|
+
send: (cmd) => {
|
|
111
|
+
if (proc.stdin.writable)
|
|
112
|
+
proc.stdin.write(JSON.stringify(cmd) + '\n');
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
all.add(p);
|
|
116
|
+
// Whole lines: a key split across two reads would escape the redaction.
|
|
117
|
+
readline.createInterface({input: proc.stderr}).on('line', (raw) => {
|
|
118
|
+
if (!raw)
|
|
119
|
+
return;
|
|
120
|
+
const line = redact(raw, credentials.values.apiKey);
|
|
121
|
+
p.stderrTail.push(line);
|
|
122
|
+
if (p.stderrTail.length > STDERR_TAIL_LINES)
|
|
123
|
+
p.stderrTail.shift();
|
|
124
|
+
if (process.env['HERMES_LOG_STDERR'])
|
|
125
|
+
console.log(`agent[${tag}] ${line}`);
|
|
126
|
+
});
|
|
127
|
+
let started!: () => void;
|
|
128
|
+
let failed!: (e: Error) => void;
|
|
129
|
+
const readyMs = readyTimeoutMs();
|
|
130
|
+
p.ready = raceIdle(new Promise<void>((resolve, reject) => {
|
|
131
|
+
started = resolve;
|
|
132
|
+
failed = reject;
|
|
133
|
+
}), readyMs).then((r) => {
|
|
134
|
+
if (r === IDLE)
|
|
135
|
+
throw new Error(`the agent startup did not finish in ${readyMs / 1000} s`);
|
|
136
|
+
p.started = true;
|
|
137
|
+
});
|
|
138
|
+
readline.createInterface({input: proc.stdout}).on('line', (line) => {
|
|
139
|
+
let ev: AgentProcessEvent;
|
|
140
|
+
try {
|
|
141
|
+
ev = JSON.parse(line);
|
|
142
|
+
} catch {
|
|
143
|
+
return console.warn(`agent[${tag}]: a stdout line is not an event`);
|
|
144
|
+
}
|
|
145
|
+
if (ev.type === 'error' || ev.type === 'fatal')
|
|
146
|
+
ev.message = redact(ev.message, credentials.values.apiKey);
|
|
147
|
+
if (ev.type === 'ready')
|
|
148
|
+
started();
|
|
149
|
+
else if (ev.type === 'fatal')
|
|
150
|
+
failed(new Error(ev.message));
|
|
151
|
+
else if (ev.type === 'session') {
|
|
152
|
+
if (p.restore !== undefined)
|
|
153
|
+
console.log(`agent: reloaded session ${p.sessionKey} in ${Date.now() - spawnedAt} ms`);
|
|
154
|
+
p.hermesSession = ev.id;
|
|
155
|
+
p.restore = undefined;
|
|
156
|
+
}
|
|
157
|
+
if (ev.type === 'stopped')
|
|
158
|
+
p.crashes = 0;
|
|
159
|
+
p.turn?.events(ev);
|
|
160
|
+
});
|
|
161
|
+
proc.on('error', failed);
|
|
162
|
+
proc.on('exit', (code, signal) => {
|
|
163
|
+
const last = p.stderrTail.at(-1);
|
|
164
|
+
failed(new Error(`the agent exited (${signal ?? code})${last ? `: ${last}` : ''}`));
|
|
165
|
+
p.beforeForget?.();
|
|
166
|
+
if (!p.disposed) {
|
|
167
|
+
console.warn(`agent[${tag}]: exited unexpectedly (${signal ?? code}); last stderr:\n` +
|
|
168
|
+
p.stderrTail.slice(-10).join('\n'));
|
|
169
|
+
const stored = p.restore ?? p.hermesSession;
|
|
170
|
+
if (p.sessionKey && stored && holdsSession(p))
|
|
171
|
+
keepStored(p, p.sessionKey, stored);
|
|
172
|
+
}
|
|
173
|
+
forget(p);
|
|
174
|
+
});
|
|
175
|
+
return p;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** An agent process in its own home, sent its init command. The credentials go over stdin, never the environment,
|
|
179
|
+
* which every tool the agent runs inherits. The cwd is root-owned, so a stray relative path never lands in runtime
|
|
180
|
+
* state. */
|
|
181
|
+
function spawnAgent(home: string, warm: boolean, credentials: Record<string, string>): ChildProcessWithoutNullStreams {
|
|
182
|
+
const proc = spawn(AGENT_PYTHON, ['-m', 'grokky_agent'], {
|
|
183
|
+
cwd: '/', detached: true,
|
|
184
|
+
env: {PATH: process.env['PATH'] ?? '/usr/bin:/bin', HOME: home, HERMES_HOME: home, TERM: 'dumb', LANG: 'C.UTF-8',
|
|
185
|
+
PYTHONUNBUFFERED: '1', PYTHONPATH: AGENT_DIR},
|
|
186
|
+
});
|
|
187
|
+
const settings = {homes: HERMES_HOMES, skillsDir: path.join(PLUGIN_DIR, 'skills'),
|
|
188
|
+
compressionThresholdTokens: COMPRESSION_THRESHOLD_TOKENS, warm};
|
|
189
|
+
const init: AgentCommand = {type: 'init', credentials, settings};
|
|
190
|
+
proc.stdin.on('error', () => {});
|
|
191
|
+
proc.stdin.write(JSON.stringify(init) + '\n');
|
|
192
|
+
return proc;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A process that died holding a session keeps its home, and the next turn reloads the store there, unless the
|
|
196
|
+
* session's processes keep dying. */
|
|
197
|
+
function keepStored(p: AgentProcess, key: string, hermesSession: string): void {
|
|
198
|
+
const crashes = p.crashes + 1;
|
|
199
|
+
if (crashes >= MAX_CRASHES)
|
|
200
|
+
return console.warn(`agent: dropped the stored state of session ${key} after ${crashes} unexpected exits`);
|
|
201
|
+
p.keepHome = true;
|
|
202
|
+
parked.set(key, {home: p.home, hermesSession, stored: Promise.resolve(), crashes});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function forget(p: AgentProcess, keepHome = false): void {
|
|
206
|
+
all.delete(p);
|
|
207
|
+
if (p.sessionKey && bySession.get(p.sessionKey) === p)
|
|
208
|
+
bySession.delete(p.sessionKey);
|
|
209
|
+
const i = spares.indexOf(p);
|
|
210
|
+
if (i >= 0)
|
|
211
|
+
spares.splice(i, 1);
|
|
212
|
+
if (!keepHome && !p.keepHome)
|
|
213
|
+
fs.rmSync(p.home, {recursive: true, force: true, maxRetries: 3});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Kills the agent and every process under it, tool commands in their own sessions included. */
|
|
217
|
+
export function dispose(p: AgentProcess, reason: string): void {
|
|
218
|
+
if (p.disposed)
|
|
219
|
+
return;
|
|
220
|
+
p.disposed = true;
|
|
221
|
+
// An exited child's pid may already belong to another process.
|
|
222
|
+
const failed = p.proc.pid && !hasExited(p) ? killTree(p.proc.pid) : [];
|
|
223
|
+
console.log(`agent[${path.basename(p.home).slice(0, 8)}]: dispose (${reason})` +
|
|
224
|
+
(failed.length ? `; could not signal ${failed.join(', ')}` : ''));
|
|
225
|
+
forget(p);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function topUpSpares(): void {
|
|
229
|
+
const credentials = spareCredentials;
|
|
230
|
+
if (!credentials)
|
|
231
|
+
return;
|
|
232
|
+
const ready = () => spares.filter((s) => s.credentials.id === credentials.id).length;
|
|
233
|
+
const unclaimed = () => starting.filter((e) => !e.claimed && e.credentials.id === credentials.id).length;
|
|
234
|
+
while (ready() + unclaimed() < WARM_SPARES && all.size < MAX_PROCESSES) {
|
|
235
|
+
const entry = {proc: spawnProcess(credentials), claimed: false, credentials};
|
|
236
|
+
starting.push(entry);
|
|
237
|
+
entry.proc.then(async (s) => {
|
|
238
|
+
try {
|
|
239
|
+
await s.ready;
|
|
240
|
+
if (!entry.claimed)
|
|
241
|
+
spares.push(s);
|
|
242
|
+
} catch (e: any) {
|
|
243
|
+
console.warn('agent: warm spare failed to start:', e.message);
|
|
244
|
+
dispose(s, 'spare failed');
|
|
245
|
+
}
|
|
246
|
+
}).catch((e) => console.warn('agent: warm spare spawn failed:', e.message))
|
|
247
|
+
.finally(() => starting.splice(starting.indexOf(entry), 1));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function takeSpare(credentials: ProviderCredentials): Promise<AgentProcess | undefined> {
|
|
252
|
+
const i = spares.findIndex((s) => s.credentials.id === credentials.id);
|
|
253
|
+
if (i >= 0)
|
|
254
|
+
return spares.splice(i, 1)[0];
|
|
255
|
+
const entry = starting.find((e) => !e.claimed && e.credentials.id === credentials.id);
|
|
256
|
+
if (!entry)
|
|
257
|
+
return undefined;
|
|
258
|
+
entry.claimed = true;
|
|
259
|
+
return entry.proc.catch(() => undefined);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Ends the session's process but keeps its Hermes session store, so the next turn reloads it.
|
|
263
|
+
* The store moves once the process has exited, so no write of the dying agent is lost. */
|
|
264
|
+
function evict(p: AgentProcess, why: string): void {
|
|
265
|
+
console.log(`agent: evicting session ${p.sessionKey} (${why}); ${bySession.size - 1} session(s) remain live`);
|
|
266
|
+
const key = p.sessionKey;
|
|
267
|
+
if (!key || !p.hermesSession || !holdsSession(p) || p.disposed)
|
|
268
|
+
return dispose(p, why);
|
|
269
|
+
p.disposed = true;
|
|
270
|
+
forget(p, true);
|
|
271
|
+
const home = path.join(PARKED_DIR, randomUUID());
|
|
272
|
+
fs.mkdirSync(home, {recursive: true, mode: 0o700});
|
|
273
|
+
let stored!: () => void;
|
|
274
|
+
const parkedSession: ParkedSession = {home, hermesSession: p.hermesSession,
|
|
275
|
+
stored: new Promise<void>((resolve) => { stored = resolve; })};
|
|
276
|
+
p.beforeForget = () => {
|
|
277
|
+
p.beforeForget = undefined;
|
|
278
|
+
for (const f of fs.existsSync(p.home) ? fs.readdirSync(p.home).filter((n) => SESSION_STATE.test(n)) : [])
|
|
279
|
+
fs.renameSync(path.join(p.home, f), path.join(home, f));
|
|
280
|
+
fs.rmSync(p.home, {recursive: true, force: true, maxRetries: 3});
|
|
281
|
+
stored();
|
|
282
|
+
};
|
|
283
|
+
// No exit is coming for a process that has exited or could not be signalled: its store moves now.
|
|
284
|
+
if (hasExited(p) || !p.proc.pid || killTree(p.proc.pid).includes(p.proc.pid))
|
|
285
|
+
p.beforeForget();
|
|
286
|
+
parked.set(key, parkedSession);
|
|
287
|
+
trimParked();
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function trimParked(): void {
|
|
291
|
+
for (const [key, s] of parked) {
|
|
292
|
+
if (parked.size + bySession.size <= MAX_SESSIONS)
|
|
293
|
+
return;
|
|
294
|
+
parked.delete(key);
|
|
295
|
+
fs.rmSync(s.home, {recursive: true, force: true, maxRetries: 3});
|
|
296
|
+
console.log(`agent: dropped the stored state of session ${key} (cap ${MAX_SESSIONS} sessions)`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Ends the session's process and keeps its history: the next turn reloads it. */
|
|
301
|
+
export function parkSession(key: string, reason: string): void {
|
|
302
|
+
const p = bySession.get(key);
|
|
303
|
+
if (p)
|
|
304
|
+
evict(p, reason);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function dropSession(key: string, reason: string): void {
|
|
308
|
+
const p = bySession.get(key);
|
|
309
|
+
if (p)
|
|
310
|
+
dispose(p, reason);
|
|
311
|
+
const s = parked.get(key);
|
|
312
|
+
if (s) {
|
|
313
|
+
parked.delete(key);
|
|
314
|
+
fs.rmSync(s.home, {recursive: true, force: true, maxRetries: 3});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Back under the process cap (a busy session is never evicted, so the pool can run over it). */
|
|
319
|
+
function evictForRoom(): void {
|
|
320
|
+
while (all.size >= MAX_PROCESSES) {
|
|
321
|
+
const stale = spares.findIndex((s) => s.credentials.id !== spareCredentials?.id);
|
|
322
|
+
const spare = spares.splice(stale >= 0 ? stale : 0, 1)[0];
|
|
323
|
+
if (spare) {
|
|
324
|
+
dispose(spare, 'room for a session');
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
const idle = [...bySession.values()].filter((p) => p.started && !p.turn)
|
|
328
|
+
.sort((a, b) => a.lastUsed - b.lastUsed)[0];
|
|
329
|
+
if (!idle)
|
|
330
|
+
return;
|
|
331
|
+
evict(idle, `LRU, cap ${MAX_PROCESSES}`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function reapIdle(now = Date.now()): void {
|
|
336
|
+
for (const p of [...bySession.values()]) {
|
|
337
|
+
if (p.started && !p.turn && now - p.lastUsed > IDLE_TTL_MS)
|
|
338
|
+
evict(p, `idle ${Math.round((now - p.lastUsed) / 60_000)} min`);
|
|
339
|
+
}
|
|
340
|
+
// Spares of rotated keys or of groups gone quiet would otherwise hold their key and memory for good.
|
|
341
|
+
for (const s of spares.filter((s) => s.credentials.id !== spareCredentials?.id && now - s.lastUsed > IDLE_TTL_MS))
|
|
342
|
+
dispose(s, 'idle spare of other credentials');
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const startError = (e: any) => new Error(`The assistant could not start: ${e?.message ?? e}`);
|
|
346
|
+
|
|
347
|
+
/** The session's process. A live one is returned whatever its credentials: the caller parks it when they differ. */
|
|
348
|
+
export async function acquire(sessionKey: string, credentials: ProviderCredentials): Promise<AgentProcess> {
|
|
349
|
+
const existing = bySession.get(sessionKey);
|
|
350
|
+
if (existing) {
|
|
351
|
+
await existing.ready.catch((e) => {
|
|
352
|
+
throw startError(e);
|
|
353
|
+
});
|
|
354
|
+
existing.lastUsed = Date.now();
|
|
355
|
+
return existing;
|
|
356
|
+
}
|
|
357
|
+
// Taken before eviction makes room, which could otherwise trim this very session.
|
|
358
|
+
const stored = parked.get(sessionKey);
|
|
359
|
+
parked.delete(sessionKey);
|
|
360
|
+
let p: AgentProcess | undefined;
|
|
361
|
+
try {
|
|
362
|
+
// A warm spare needs no room; a process started for this session does.
|
|
363
|
+
p = stored ? undefined : await takeSpare(credentials);
|
|
364
|
+
if (!p) {
|
|
365
|
+
evictForRoom();
|
|
366
|
+
p = await spawnProcess(credentials, stored);
|
|
367
|
+
}
|
|
368
|
+
} catch (e) {
|
|
369
|
+
if (stored && !(e instanceof SessionLost))
|
|
370
|
+
parked.set(sessionKey, stored);
|
|
371
|
+
throw e;
|
|
372
|
+
}
|
|
373
|
+
p.sessionKey = sessionKey;
|
|
374
|
+
p.lastUsed = Date.now();
|
|
375
|
+
bySession.set(sessionKey, p);
|
|
376
|
+
trimParked();
|
|
377
|
+
// Credentials not yet seen to start an agent warm no spares.
|
|
378
|
+
if (spareCredentials?.id === credentials.id)
|
|
379
|
+
topUpSpares();
|
|
380
|
+
try {
|
|
381
|
+
await p.ready;
|
|
382
|
+
} catch (e: any) {
|
|
383
|
+
// A stored session stays stored: a transient failure must not cost its history. The turn errors (no
|
|
384
|
+
// session_reset, which would replay the transcript on top of that history); the next one retries.
|
|
385
|
+
if (stored) {
|
|
386
|
+
p.keepHome = true;
|
|
387
|
+
parked.set(sessionKey, stored);
|
|
388
|
+
}
|
|
389
|
+
dispose(p, 'failed to start');
|
|
390
|
+
throw startError(e);
|
|
391
|
+
}
|
|
392
|
+
if (spareCredentials?.id !== credentials.id) {
|
|
393
|
+
spareCredentials = credentials;
|
|
394
|
+
topUpSpares();
|
|
395
|
+
}
|
|
396
|
+
return p;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function disposeAll(reason: string): void {
|
|
400
|
+
for (const p of [...all])
|
|
401
|
+
dispose(p, reason);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function startPool(): void {
|
|
405
|
+
fs.mkdirSync(HERMES_HOMES, {recursive: true, mode: 0o700});
|
|
406
|
+
// Homes of a previous run (container restart, crash) belong to processes that no longer exist.
|
|
407
|
+
for (const entry of fs.readdirSync(HERMES_HOMES))
|
|
408
|
+
fs.rmSync(path.join(HERMES_HOMES, entry), {recursive: true, force: true});
|
|
409
|
+
setInterval(() => reapIdle(), 60_000).unref();
|
|
410
|
+
startOrphanReaper(ownedPids);
|
|
411
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type {AgentEvent, AgentProcessEvent, AgentTurnRequest} from '../types';
|
|
2
|
+
import {toolSummary} from '../tool-summary';
|
|
3
|
+
import {bareToolName} from '../verify';
|
|
4
|
+
import {killDescendants} from '../watchdog';
|
|
5
|
+
import {acquire, dropSession, hasExited, hasSession, parkSession, processForSession, SessionLost} from './pool';
|
|
6
|
+
import type {AgentProcess} from './pool';
|
|
7
|
+
|
|
8
|
+
class Channel<T> {
|
|
9
|
+
private queue: T[] = [];
|
|
10
|
+
private waiters: ((r: IteratorResult<T, undefined>) => void)[] = [];
|
|
11
|
+
private closed = false;
|
|
12
|
+
|
|
13
|
+
push(v: T): void {
|
|
14
|
+
if (this.closed)
|
|
15
|
+
return;
|
|
16
|
+
const w = this.waiters.shift();
|
|
17
|
+
if (w)
|
|
18
|
+
w({value: v, done: false});
|
|
19
|
+
else
|
|
20
|
+
this.queue.push(v);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
end(): void {
|
|
24
|
+
this.closed = true;
|
|
25
|
+
for (const w of this.waiters.splice(0))
|
|
26
|
+
w({value: undefined, done: true});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
next(): Promise<IteratorResult<T, undefined>> {
|
|
30
|
+
if (this.queue.length)
|
|
31
|
+
return Promise.resolve({value: this.queue.shift()!, done: false});
|
|
32
|
+
if (this.closed)
|
|
33
|
+
return Promise.resolve({value: undefined, done: true});
|
|
34
|
+
return new Promise((resolve) => this.waiters.push(resolve));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Runs one turn on the session's agent process: gate feedback continues it, browser calls go to the tab.
|
|
39
|
+
* The iterator ends after the terminal event, or silently once `req.signal` aborts. */
|
|
40
|
+
export function runTurn(req: AgentTurnRequest): AsyncIterator<AgentEvent, undefined> {
|
|
41
|
+
const chan = new Channel<AgentEvent>();
|
|
42
|
+
let p: AgentProcess | undefined;
|
|
43
|
+
let finish!: () => void;
|
|
44
|
+
const settled = new Promise<void>((resolve) => { finish = resolve; });
|
|
45
|
+
const onExit = (): void => {
|
|
46
|
+
const last = p?.stderrTail.at(-1);
|
|
47
|
+
chan.push({type: 'error', message: `The assistant stopped unexpectedly${last ? `: ${last}` : '.'}`});
|
|
48
|
+
finish();
|
|
49
|
+
};
|
|
50
|
+
const sessionLost = (): void => {
|
|
51
|
+
dropSession(req.sessionKey, 'stored session lost');
|
|
52
|
+
chan.push({type: 'session_reset'});
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const onEvent = (ev: AgentProcessEvent): void => {
|
|
56
|
+
switch (ev.type) {
|
|
57
|
+
case 'text':
|
|
58
|
+
case 'activity':
|
|
59
|
+
case 'usage':
|
|
60
|
+
return chan.push(ev);
|
|
61
|
+
case 'tool_start':
|
|
62
|
+
return chan.push({type: 'tool_activity', name: bareToolName(ev.name), summary: toolSummary(ev.name, ev.args)});
|
|
63
|
+
case 'tool_end':
|
|
64
|
+
for (const g of req.gates)
|
|
65
|
+
g.afterTool(ev.name, ev.args, ev.result);
|
|
66
|
+
return chan.push({type: 'activity'});
|
|
67
|
+
case 'browser_call':
|
|
68
|
+
req.awaitBrowser(ev.name, ev.input, ev.timeoutMs).then(
|
|
69
|
+
(value) => p?.send({type: 'browser_result', id: ev.id, value}),
|
|
70
|
+
(e) => p?.send({type: 'browser_result', id: ev.id, error: String(e?.message ?? e)}));
|
|
71
|
+
return chan.push({type: 'activity'});
|
|
72
|
+
case 'browser_show':
|
|
73
|
+
req.showInBrowser(ev.name, ev.input);
|
|
74
|
+
return chan.push({type: 'activity'});
|
|
75
|
+
case 'stopped': {
|
|
76
|
+
const feedback = req.gates.map((g) => g.atStop()).filter((f): f is string => !!f);
|
|
77
|
+
if (feedback.length && !req.signal.aborted)
|
|
78
|
+
return p?.send({type: 'continue', text: feedback.join('\n\n')});
|
|
79
|
+
chan.push({type: 'result', text: ev.text, structuredOutput: ev.structuredOutput, metrics: ev.metrics});
|
|
80
|
+
return finish();
|
|
81
|
+
}
|
|
82
|
+
case 'limit':
|
|
83
|
+
case 'error':
|
|
84
|
+
chan.push(ev);
|
|
85
|
+
return finish();
|
|
86
|
+
case 'session_lost':
|
|
87
|
+
sessionLost();
|
|
88
|
+
return finish();
|
|
89
|
+
case 'cancelled':
|
|
90
|
+
return finish();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const drive = async (): Promise<void> => {
|
|
95
|
+
if (req.signal.aborted)
|
|
96
|
+
return;
|
|
97
|
+
for (;;) {
|
|
98
|
+
// Checked with nothing awaited before `acquire` takes the session, so it cannot vanish in between.
|
|
99
|
+
if (req.resumeExpected && !hasSession(req.sessionKey))
|
|
100
|
+
return chan.push({type: 'session_reset'});
|
|
101
|
+
p = await acquire(req.sessionKey, req.credentials);
|
|
102
|
+
// A cancelled turn ends a moment after the abort that ended it on this side.
|
|
103
|
+
for (let prev = p.turn; prev; prev = p.turn)
|
|
104
|
+
await prev.settled;
|
|
105
|
+
if (req.signal.aborted)
|
|
106
|
+
return;
|
|
107
|
+
// The process may have exited as the turn before this one ended; the next acquire starts another.
|
|
108
|
+
if (hasExited(p))
|
|
109
|
+
continue;
|
|
110
|
+
if (p.credentials.id === req.credentials.id)
|
|
111
|
+
break;
|
|
112
|
+
// Rotated keys or another group: the history is reloaded by a process started with this turn's credentials.
|
|
113
|
+
parkSession(req.sessionKey, 'credentials changed');
|
|
114
|
+
}
|
|
115
|
+
p.turn = {events: onEvent, settled};
|
|
116
|
+
p.proc.once('exit', onExit);
|
|
117
|
+
p.turns++;
|
|
118
|
+
p.send({type: 'turn', text: req.text, images: req.images, systemPrompt: req.systemPrompt, effort: req.effort,
|
|
119
|
+
cwd: req.cwd, userDir: req.userDir, outputSchema: req.outputSchema,
|
|
120
|
+
clientTools: req.clientTools, browserTools: req.browserTools, datagrokMcp: req.datagrokMcp, limits: req.limits,
|
|
121
|
+
restore: p.restore});
|
|
122
|
+
await settled;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
req.signal.addEventListener('abort', () => {
|
|
126
|
+
const proc = processForSession(req.sessionKey);
|
|
127
|
+
if (proc?.turn?.settled === settled) {
|
|
128
|
+
proc.send({type: 'cancel', reason: (req.signal.reason as Error | undefined)?.message});
|
|
129
|
+
// Hermes stops the tool it is running, but not what that tool started in a session of its own.
|
|
130
|
+
void settled.then(() => {
|
|
131
|
+
if (!proc.disposed && proc.proc.pid)
|
|
132
|
+
killDescendants(proc.proc.pid);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
chan.end();
|
|
136
|
+
}, {once: true});
|
|
137
|
+
|
|
138
|
+
drive().catch((e: any) => {
|
|
139
|
+
if (e instanceof SessionLost)
|
|
140
|
+
return sessionLost();
|
|
141
|
+
if (!req.signal.aborted)
|
|
142
|
+
chan.push({type: 'error', message: String(e?.message ?? e)});
|
|
143
|
+
}).finally(() => {
|
|
144
|
+
finish();
|
|
145
|
+
p?.proc.off('exit', onExit);
|
|
146
|
+
if (p?.turn?.settled === settled) {
|
|
147
|
+
p.turn = null;
|
|
148
|
+
p.lastUsed = Date.now();
|
|
149
|
+
}
|
|
150
|
+
chan.end();
|
|
151
|
+
});
|
|
152
|
+
return {next: () => chan.next()};
|
|
153
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const WORKSPACE = process.env['CLAUDE_WORKSPACE'] || '/workspace';
|
|
2
|
+
|
|
3
|
+
export function rewriteForDocker(url: string): string {
|
|
4
|
+
return url.replace('//localhost', '//host.docker.internal');
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function apiUrlFromMcpUrl(mcpUrl: string): string | undefined {
|
|
8
|
+
const idx = mcpUrl.indexOf('/docker/containers/proxy/');
|
|
9
|
+
return idx > 0 ? mcpUrl.substring(0, idx) : undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const PLUGIN_DIR = process.env['GROKKY_PLUGIN_DIR'] || '/app/plugin';
|
|
13
|
+
export const AGENT_DIR = process.env['GROKKY_AGENT_DIR'] || '/app/agent';
|
|
14
|
+
export const AGENT_PYTHON = process.env['GROKKY_AGENT_PYTHON'] || '/opt/hermes/.venv/bin/python';
|
|
15
|
+
// Not under /tmp, which an agent may clear.
|
|
16
|
+
export const HERMES_HOMES = process.env['GROKKY_HERMES_HOMES'] || '/var/lib/grokky/hermes';
|
|
17
|
+
|
|
18
|
+
/** The keys of Grokky's package credentials handed to the agent's provider (agent/grokky_agent/providers). */
|
|
19
|
+
export const PROVIDER_CREDENTIALS = ['provider', 'apiKey', 'baseUrl', 'region', 'apiFormat', 'model', 'service',
|
|
20
|
+
'TEST_UPSTREAM'];
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {createHash} from 'node:crypto';
|
|
2
|
+
import {PROVIDER_CREDENTIALS, rewriteForDocker} from './constants';
|
|
3
|
+
|
|
4
|
+
export const CONTAINER_TOKEN_HEADER = 'x-datagrok-container-token';
|
|
5
|
+
|
|
6
|
+
/** `id` tells two sets apart without exposing the values. */
|
|
7
|
+
export interface ProviderCredentials {
|
|
8
|
+
values: Record<string, string>;
|
|
9
|
+
id: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function providerCredentials(values: Record<string, string>): ProviderCredentials {
|
|
13
|
+
return {values, id: createHash('sha256').update(JSON.stringify(Object.entries(values).sort())).digest('hex')};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const API_URL = process.env.DATAGROK_API_URL && rewriteForDocker(process.env.DATAGROK_API_URL);
|
|
17
|
+
const NOT_SET =
|
|
18
|
+
'No AI model credentials are set for you: an administrator sets them in Plugins | Grokky | Credentials...';
|
|
19
|
+
const failed = (why: string) => new Error(`The assistant could not read its credentials: ${why}`);
|
|
20
|
+
|
|
21
|
+
/** Grokky's package credentials for the user whose connection brought `token`, resolved by their groups. */
|
|
22
|
+
export async function userCredentials(token?: string): Promise<ProviderCredentials> {
|
|
23
|
+
if (!API_URL)
|
|
24
|
+
throw failed('DATAGROK_API_URL is not set');
|
|
25
|
+
if (!token)
|
|
26
|
+
throw failed('the connection did not come through Datagrok');
|
|
27
|
+
const res = await fetch(`${API_URL}/docker/credentials`,
|
|
28
|
+
{headers: {Authorization: `Bearer ${token}`}, signal: AbortSignal.timeout(10_000)})
|
|
29
|
+
.catch((e: Error) => Promise.reject(failed(e.message)));
|
|
30
|
+
const status = Number(res.headers.get('api-error-code') ?? res.status);
|
|
31
|
+
if (!res.ok || res.headers.has('api-error')) {
|
|
32
|
+
await res.body?.cancel();
|
|
33
|
+
throw status === 404 ? new Error(NOT_SET) : failed(`HTTP ${status} from /docker/credentials`);
|
|
34
|
+
}
|
|
35
|
+
const all: Record<string, unknown> = await res.json().catch(() => Promise.reject(failed('the answer is not JSON')));
|
|
36
|
+
const values: Record<string, string> = {};
|
|
37
|
+
for (const k of PROVIDER_CREDENTIALS) {
|
|
38
|
+
const v = all[k];
|
|
39
|
+
if (typeof v === 'string' && v)
|
|
40
|
+
values[k] = v;
|
|
41
|
+
}
|
|
42
|
+
if (!Object.keys(values).length)
|
|
43
|
+
throw new Error(NOT_SET);
|
|
44
|
+
return providerCredentials(values);
|
|
45
|
+
}
|