@lornatang/dsh-caveman 0.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/CHANGELOG.md +16 -0
- package/LICENSE +202 -0
- package/LICENSE-MIT +21 -0
- package/NOTICE +51 -0
- package/README.md +218 -0
- package/README.zh.md +218 -0
- package/cordis.patch.yml +3 -0
- package/examples/caveman-anthropic.patch.yml +14 -0
- package/examples/caveman-auto.patch.yml +15 -0
- package/lib/attribution.js +24 -0
- package/lib/blocks.js +80 -0
- package/lib/cavecrew-git.js +83 -0
- package/lib/cavecrew.js +67 -0
- package/lib/compression.js +434 -0
- package/lib/index.js +127 -0
- package/lib/memory.js +35 -0
- package/lib/mode.js +71 -0
- package/lib/native.js +357 -0
- package/lib/runtime.js +199 -0
- package/lib/skills.js +75 -0
- package/lib/stats.js +189 -0
- package/lib/types/attribution.d.ts +8 -0
- package/lib/types/blocks.d.ts +12 -0
- package/lib/types/cavecrew-git.d.ts +5 -0
- package/lib/types/cavecrew.d.ts +10 -0
- package/lib/types/compression.d.ts +50 -0
- package/lib/types/index.d.ts +30 -0
- package/lib/types/memory.d.ts +3 -0
- package/lib/types/mode.d.ts +33 -0
- package/lib/types/native.d.ts +43 -0
- package/lib/types/runtime.d.ts +23 -0
- package/lib/types/skills.d.ts +3 -0
- package/lib/types/stats.d.ts +6 -0
- package/package.json +129 -0
- package/presets/cavecrew.patch.yml +54 -0
- package/scripts/benchmark.mjs +79 -0
- package/scripts/caveman-cli.mjs +30 -0
- package/scripts/learn-binary.mjs +82 -0
- package/scripts/learn-checksums.json +29 -0
- package/vendor/caveman/LICENSE +202 -0
- package/vendor/caveman/LICENSE-MIT +21 -0
- package/vendor/caveman/NOTICE +49 -0
- package/vendor/caveman/agents/cavecrew-builder.md +46 -0
- package/vendor/caveman/agents/cavecrew-investigator.md +56 -0
- package/vendor/caveman/agents/cavecrew-reviewer.md +47 -0
- package/vendor/caveman/skills/activation-rule.mjs +43 -0
- package/vendor/caveman/skills/cavecrew/README.md +67 -0
- package/vendor/caveman/skills/cavecrew/SKILL.md +78 -0
- package/vendor/caveman/skills/caveman/README.md +68 -0
- package/vendor/caveman/skills/caveman/SKILL.md +89 -0
- package/vendor/caveman/skills/caveman-commit/README.md +44 -0
- package/vendor/caveman/skills/caveman-commit/SKILL.md +63 -0
- package/vendor/caveman/skills/caveman-compress/README.md +262 -0
- package/vendor/caveman/skills/caveman-compress/SECURITY.md +55 -0
- package/vendor/caveman/skills/caveman-compress/SKILL.md +114 -0
- package/vendor/caveman/skills/caveman-compress/scripts/__init__.py +9 -0
- package/vendor/caveman/skills/caveman-compress/scripts/__main__.py +3 -0
- package/vendor/caveman/skills/caveman-compress/scripts/benchmark.py +80 -0
- package/vendor/caveman/skills/caveman-compress/scripts/cli.py +94 -0
- package/vendor/caveman/skills/caveman-compress/scripts/compress.py +1331 -0
- package/vendor/caveman/skills/caveman-compress/scripts/detect.py +192 -0
- package/vendor/caveman/skills/caveman-compress/scripts/validate.py +440 -0
- package/vendor/caveman/skills/caveman-discover/SKILL.md +115 -0
- package/vendor/caveman/skills/caveman-evidence-review/SKILL.md +142 -0
- package/vendor/caveman/skills/caveman-explore/SKILL.md +42 -0
- package/vendor/caveman/skills/caveman-explore/package.json +12 -0
- package/vendor/caveman/skills/caveman-explore/tests/skill-file.test.mjs +44 -0
- package/vendor/caveman/skills/caveman-help/README.md +39 -0
- package/vendor/caveman/skills/caveman-help/SKILL.md +62 -0
- package/vendor/caveman/skills/caveman-learn/CLAUDE.md +32 -0
- package/vendor/caveman/skills/caveman-learn/README.md +38 -0
- package/vendor/caveman/skills/caveman-learn/SKILL.md +185 -0
- package/vendor/caveman/skills/caveman-learn/package.json +12 -0
- package/vendor/caveman/skills/caveman-learn/tests/index.js +1 -0
- package/vendor/caveman/skills/caveman-learn/tests/skill-file.test.mjs +54 -0
- package/vendor/caveman/skills/caveman-manage/SKILL.md +112 -0
- package/vendor/caveman/skills/caveman-optimize/SKILL.md +111 -0
- package/vendor/caveman/skills/caveman-review/README.md +33 -0
- package/vendor/caveman/skills/caveman-review/SKILL.md +53 -0
- package/vendor/caveman/skills/caveman-setup/SKILL.md +222 -0
- package/vendor/caveman/skills/caveman-stats/README.md +48 -0
- package/vendor/caveman/skills/caveman-stats/SKILL.md +17 -0
- package/vendor/caveman/skills/compile.mjs +298 -0
- package/vendor/caveman/skills/engine-mcp-tools.json +10 -0
- package/vendor/caveman/skills/generated/aider/pack.json +163 -0
- package/vendor/caveman/skills/generated/claude/pack.json +163 -0
- package/vendor/caveman/skills/generated/codex/pack.json +163 -0
- package/vendor/caveman/skills/generated/gemini/pack.json +163 -0
- package/vendor/caveman/skills/generated/hermes/pack.json +163 -0
- package/vendor/caveman/skills/generated/opencode/pack.json +163 -0
- package/vendor/caveman/skills/investigate-first/SKILL.md +16 -0
- package/vendor/caveman/skills/investigate-first/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/lean-build/SKILL.md +18 -0
- package/vendor/caveman/skills/lean-build/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/megacave/README.md +11 -0
- package/vendor/caveman/skills/megacave/SKILL.md +65 -0
- package/vendor/caveman/skills/migration/SKILL.md +17 -0
- package/vendor/caveman/skills/migration/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/native/native-core.md +16 -0
- package/vendor/caveman/skills/registry.json +283 -0
- package/vendor/caveman/skills/safe-refactor/SKILL.md +16 -0
- package/vendor/caveman/skills/safe-refactor/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/surgical-patch/SKILL.md +16 -0
- package/vendor/caveman/skills/surgical-patch/agents/openai.yaml +4 -0
- package/vendor/caveman/skills/ultracave/README.md +13 -0
- package/vendor/caveman/skills/ultracave/SKILL.md +63 -0
- package/vendor/caveman/skills/verbs-gate.mjs +213 -0
- package/vendor/caveman/skills/verify-and-stop/SKILL.md +16 -0
- package/vendor/caveman/skills/verify-and-stop/agents/openai.yaml +4 -0
- package/vendor/caveman/src/hooks/caveman-config.js +921 -0
- package/vendor/caveman/src/hooks/caveman-parse.js +342 -0
- package/vendor/caveman/src/hooks/package.json +3 -0
package/lib/native.js
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { open, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import { connect } from 'node:net';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join, resolve, win32 } from 'node:path';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
8
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
9
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
10
|
+
import { cavemanSessionId } from './attribution.js';
|
|
11
|
+
import { verifiedRuntime } from './runtime.js';
|
|
12
|
+
import { isManagedTool } from './compression.js';
|
|
13
|
+
const profiles = new Set(['record-only', 'core', 'core-lean-build', 'ledger', 'ccr-masking', 'cache-aware', 'full-safe', 'full-max']);
|
|
14
|
+
const stopwords = new Set(['about', 'after', 'again', 'agent', 'before', 'build', 'change', 'code', 'could', 'create', 'does', 'from', 'have', 'help', 'implement', 'into', 'make', 'please', 'project', 'repository', 'should', 'spec', 'task', 'that', 'their', 'then', 'there', 'these', 'they', 'this', 'through', 'user', 'want', 'what', 'when', 'where', 'which', 'with', 'would', 'your']);
|
|
15
|
+
/** Confirm that the model's assembled tool surface includes the admitted MCP recovery tool. */
|
|
16
|
+
export function recoveryIsPublished(assembly, tool) {
|
|
17
|
+
const direct = assembly.tools.find(entry => entry.name === tool.name);
|
|
18
|
+
if (direct && direct.description === tool.description && isDeepStrictEqual(direct.parameters, tool.parameters))
|
|
19
|
+
return true;
|
|
20
|
+
if (!assembly.tools.some(entry => entry.name === 'run_code'))
|
|
21
|
+
return false;
|
|
22
|
+
const sdk = assembly.sections.find(section => section.name === 'tools:sdk' && section.interpolate === false)?.text ?? '';
|
|
23
|
+
return (sdk.includes('declare const tools:') && sdk.split(`\n ${tool.name}:`).length >= 3) ||
|
|
24
|
+
(sdk.includes('tools: Tools') && sdk.includes(`async def ${tool.name}(`));
|
|
25
|
+
}
|
|
26
|
+
/** Hash and classify the prompt locally; the runtime does not receive the prompt text. */
|
|
27
|
+
export function nativePrompt(prompt) {
|
|
28
|
+
const text = prompt.toLowerCase();
|
|
29
|
+
const type = /\b(migrat(?:e|ion)|schema change|backfill|rollback)\b/u.test(text) ? 'migration'
|
|
30
|
+
: /\b(bug|fix|broken|regression|crash|error|fails?|incorrect)\b/u.test(text) ? 'bugfix'
|
|
31
|
+
: /\b(investigat(?:e|ion)|diagnos(?:e|is)|root cause|why does|trace)\b/u.test(text) ? 'investigation'
|
|
32
|
+
: /\b(refactor|restructure|reorganize|cleanup|clean up)\b/u.test(text) ? 'refactor'
|
|
33
|
+
: /\b(review|audit|critique|assess)\b/u.test(text) ? 'review'
|
|
34
|
+
: /\b(verif(?:y|ication)|test only|prove|validate|check that)\b/u.test(text) ? 'verification'
|
|
35
|
+
: /\b(build|implement|add|create|ship|feature)\b/u.test(text) ? 'feature' : 'general';
|
|
36
|
+
const seen = new Set();
|
|
37
|
+
for (const raw of prompt.match(/[A-Za-z][A-Za-z0-9_./-]{2,63}/gu) ?? []) {
|
|
38
|
+
const term = raw.toLowerCase().replace(/^[-./]+|[-./]+$/gu, '');
|
|
39
|
+
if (term.length < 3 || term.length > 64 || term.includes('..') || term.startsWith('/') || stopwords.has(term) ||
|
|
40
|
+
/^(?:sk|pk|rk|ghp|github_pat|xox[baprs]|akia)[-_]/iu.test(term) || /^[a-z0-9_-]{40,}$/iu.test(term))
|
|
41
|
+
continue;
|
|
42
|
+
seen.add(term);
|
|
43
|
+
if (seen.size === 12)
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
const trimmed = text.trim();
|
|
47
|
+
const continuation = Boolean(trimmed && trimmed.length <= 160 && trimmed.split(/\s+/u).length <= 14 &&
|
|
48
|
+
/^(?:please\s+)?(?:continue|go ahead|keep going|proceed|do (?:it|that)|fix (?:it|that)|retry|try again|explain (?:it|that)|what do you mean|yes|yep|yeah|why\??|how\??)[.!?\s]*$/u.test(trimmed));
|
|
49
|
+
const bytes = Buffer.from(prompt, 'utf8');
|
|
50
|
+
return { prompt: { bytes: bytes.length, sha256: `sha256:${createHash('sha256').update(bytes).digest('hex')}` }, task_profile: { type, terms: [...seen], continuation } };
|
|
51
|
+
}
|
|
52
|
+
/** Name the same per-install socket as the local runtime. */
|
|
53
|
+
export function nativeSocketPath(home, platform = process.platform) {
|
|
54
|
+
if (platform !== 'win32')
|
|
55
|
+
return join(home, 'run', 'native.sock');
|
|
56
|
+
let folded = '';
|
|
57
|
+
for (const char of win32.resolve(home))
|
|
58
|
+
folded += String.fromCodePoint(char.toLowerCase().codePointAt(0));
|
|
59
|
+
return `\\\\.\\pipe\\caveman-native-${createHash('sha256').update(folded).digest('hex').slice(0, 16)}`;
|
|
60
|
+
}
|
|
61
|
+
function validResponse(value) {
|
|
62
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
63
|
+
return false;
|
|
64
|
+
const response = value;
|
|
65
|
+
if (response.protocol_version !== 1 || response.fail_open !== true || !['allow', 'observe', 'block', 'ask', 'defer'].includes(String(response.action)) ||
|
|
66
|
+
!['silent', 'advisory', 'user'].includes(String(response.visibility)))
|
|
67
|
+
return false;
|
|
68
|
+
if (response.policy_mode !== undefined && !['record', 'safe', 'max'].includes(String(response.policy_mode)))
|
|
69
|
+
return false;
|
|
70
|
+
if (response.profile !== undefined && !profiles.has(String(response.profile)))
|
|
71
|
+
return false;
|
|
72
|
+
for (const [key, maximum] of [['context', 65536], ['message', 4096], ['output_replacement', 2097152], ['recovery_ref', 1024], ['decision_id', 256]]) {
|
|
73
|
+
const field = response[key];
|
|
74
|
+
if (field !== undefined && (typeof field !== 'string' || Buffer.byteLength(field, 'utf8') > maximum))
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
export async function nativeCall(home, request, signal) {
|
|
80
|
+
if (signal?.aborted)
|
|
81
|
+
return undefined;
|
|
82
|
+
const payload = Buffer.from(JSON.stringify(request) + '\n');
|
|
83
|
+
if (payload.length > 2 * 1024 * 1024)
|
|
84
|
+
return undefined;
|
|
85
|
+
const attempt = () => new Promise(resolveResponse => {
|
|
86
|
+
let finished = false;
|
|
87
|
+
let connected = false;
|
|
88
|
+
let size = 0;
|
|
89
|
+
const chunks = [];
|
|
90
|
+
const socket = connect({ path: nativeSocketPath(home) });
|
|
91
|
+
const finish = (response, retry = false) => {
|
|
92
|
+
if (finished)
|
|
93
|
+
return;
|
|
94
|
+
finished = true;
|
|
95
|
+
clearTimeout(timeout);
|
|
96
|
+
signal?.removeEventListener('abort', abort);
|
|
97
|
+
socket.destroy();
|
|
98
|
+
resolveResponse({ response, retry });
|
|
99
|
+
};
|
|
100
|
+
const abort = () => finish();
|
|
101
|
+
// The runtime enforces its own 250 ms budget. Allow transport and event-loop
|
|
102
|
+
// scheduling slack, while bounding the whole request even if bytes trickle in.
|
|
103
|
+
const timeout = setTimeout(() => finish(), 750);
|
|
104
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
105
|
+
socket.once('connect', () => { connected = true; if (!finished)
|
|
106
|
+
socket.write(payload); });
|
|
107
|
+
socket.on('data', (chunk) => {
|
|
108
|
+
size += chunk.length;
|
|
109
|
+
if (size > 2 * 1024 * 1024)
|
|
110
|
+
return finish();
|
|
111
|
+
chunks.push(chunk);
|
|
112
|
+
if (chunk.includes(10)) {
|
|
113
|
+
try {
|
|
114
|
+
const line = Buffer.concat(chunks);
|
|
115
|
+
const parsed = JSON.parse(line.subarray(0, line.indexOf(10)).toString('utf8'));
|
|
116
|
+
finish(validResponse(parsed) ? parsed : undefined);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
finish();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
socket.once('end', () => {
|
|
124
|
+
try {
|
|
125
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
126
|
+
finish(validResponse(parsed) ? parsed : undefined);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
finish();
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
socket.once('error', (error) => finish(undefined, !connected && ['ENOENT', 'ECONNREFUSED'].includes(error.code ?? '')));
|
|
133
|
+
});
|
|
134
|
+
const first = await attempt();
|
|
135
|
+
if (!first.retry || signal?.aborted)
|
|
136
|
+
return first.response;
|
|
137
|
+
try {
|
|
138
|
+
await delay(40, undefined, signal ? { signal } : undefined);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
return (await attempt()).response;
|
|
144
|
+
}
|
|
145
|
+
async function inputState(ctx, cwd, input, signal) {
|
|
146
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
147
|
+
return undefined;
|
|
148
|
+
const values = input;
|
|
149
|
+
const path = [values.path, values.file_path, values.file, values.filename].find(value => typeof value === 'string' && value.trim());
|
|
150
|
+
if (typeof path !== 'string' || path.includes('\0'))
|
|
151
|
+
return undefined;
|
|
152
|
+
try {
|
|
153
|
+
const filesystem = ctx.get('fs');
|
|
154
|
+
if (!filesystem)
|
|
155
|
+
return undefined;
|
|
156
|
+
const absolute = resolve(cwd, path);
|
|
157
|
+
const resolved = await realpath(absolute);
|
|
158
|
+
const target = await filesystem.resolve(path, { cwd, signal });
|
|
159
|
+
if (filesystem.processPathFromHostPath(resolved) !== filesystem.processPath(target))
|
|
160
|
+
return undefined;
|
|
161
|
+
const file = await open(resolved, 'r');
|
|
162
|
+
try {
|
|
163
|
+
const before = await file.stat();
|
|
164
|
+
if (!before.isFile() || before.size > 8 * 1024 * 1024)
|
|
165
|
+
return undefined;
|
|
166
|
+
const content = await file.readFile({ signal: AbortSignal.any([signal, AbortSignal.timeout(250)]) });
|
|
167
|
+
const [after, current, currentPath] = await Promise.all([file.stat(), stat(absolute), realpath(absolute)]);
|
|
168
|
+
if (currentPath !== resolved || content.length !== before.size ||
|
|
169
|
+
[after, current].some(info => info.dev !== before.dev || info.ino !== before.ino || info.size !== before.size ||
|
|
170
|
+
info.mtimeMs !== before.mtimeMs || info.ctimeMs !== before.ctimeMs || info.mode !== before.mode))
|
|
171
|
+
return undefined;
|
|
172
|
+
const hash = createHash('sha256').update(resolved).update('\0').update(JSON.stringify(input)).update('\0').update(content);
|
|
173
|
+
return `sha256:${hash.digest('hex')}`;
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
await file.close();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
async function runtimeInstance(endpoint, home, signal) {
|
|
184
|
+
if (!await verifiedRuntime(endpoint, process.env, signal))
|
|
185
|
+
return undefined;
|
|
186
|
+
try {
|
|
187
|
+
const port = Number(new URL(endpoint).port || 80);
|
|
188
|
+
const token = JSON.parse(readFileSync(join(home, 'run', `${port}.json`), 'utf8')).instance_token;
|
|
189
|
+
return typeof token === 'string' && token ? token : undefined;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Add dynamic native task context when the verified local runtime is running. */
|
|
196
|
+
export function registerNative(ctx, endpoint, policy) {
|
|
197
|
+
const sessions = new WeakMap();
|
|
198
|
+
const owners = new WeakMap();
|
|
199
|
+
const selections = new WeakMap();
|
|
200
|
+
const pending = new Set();
|
|
201
|
+
const home = process.env.CAVEMAN_HOME ?? join(homedir(), '.caveman');
|
|
202
|
+
ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
|
203
|
+
const result = await next();
|
|
204
|
+
if (context.agent && context.toolSet)
|
|
205
|
+
selections.set(context.agent, context.toolSet);
|
|
206
|
+
return result;
|
|
207
|
+
});
|
|
208
|
+
ctx.on('agent/pre-step', async ({ agent, modelSelection, signal }, next) => {
|
|
209
|
+
const decision = await next();
|
|
210
|
+
if (decision.kind === 'reject')
|
|
211
|
+
return decision;
|
|
212
|
+
const preset = ctx.get('agentPresets')?.composedPreset(agent.ctx);
|
|
213
|
+
const specialized = preset === 'cavecrew-investigator' || preset === 'cavecrew-builder' || preset === 'cavecrew-reviewer';
|
|
214
|
+
const existing = sessions.get(agent);
|
|
215
|
+
if (existing?.queue)
|
|
216
|
+
await existing.queue;
|
|
217
|
+
const toolSet = selections.get(agent);
|
|
218
|
+
let recovery;
|
|
219
|
+
const recoveryVisible = () => recovery ??= (async () => {
|
|
220
|
+
if (!toolSet)
|
|
221
|
+
return false;
|
|
222
|
+
const tool = ctx.tools.get('mcp__caveman__caveman_retrieve', agent, toolSet);
|
|
223
|
+
if (!tool)
|
|
224
|
+
return false;
|
|
225
|
+
try {
|
|
226
|
+
return recoveryIsPublished(await ctx.systemPrompt.assemble({ scope: agent, agent, modelSelection, toolSet, signal }), tool);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
signal.throwIfAborted();
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
})();
|
|
233
|
+
const hasReference = (message) => message.source.kind === 'dsh-caveman-native' &&
|
|
234
|
+
message.content.some(block => block.type === 'text' && block.text.includes('ccr://'));
|
|
235
|
+
const working = decision.messages.some(hasReference) && !await recoveryVisible()
|
|
236
|
+
? { ...decision, messages: decision.messages.filter(message => !hasReference(message)) } : decision;
|
|
237
|
+
const contexts = [];
|
|
238
|
+
for (const text of policy.core && !specialized ? existing?.contexts.splice(0) ?? [] : []) {
|
|
239
|
+
if (!text.includes('ccr://') || await recoveryVisible())
|
|
240
|
+
contexts.push(text);
|
|
241
|
+
}
|
|
242
|
+
const withContexts = () => {
|
|
243
|
+
if (!contexts.length)
|
|
244
|
+
return working;
|
|
245
|
+
const reminder = createUserMessage({ source: { kind: 'dsh-caveman-native', form: 'notice' }, content: [{ type: 'text', text: contexts.join('\n\n') }] });
|
|
246
|
+
return { ...working, messages: [...working.messages, reminder] };
|
|
247
|
+
};
|
|
248
|
+
const prompts = working.messages.filter(message => message.source.kind === 'user')
|
|
249
|
+
.map(message => message.content.filter(block => block.type === 'text').map(block => block.text).join('\n')).filter(Boolean);
|
|
250
|
+
if (!prompts.length)
|
|
251
|
+
return withContexts();
|
|
252
|
+
const instance = await runtimeInstance(endpoint, home, signal);
|
|
253
|
+
if (!instance) {
|
|
254
|
+
sessions.delete(agent);
|
|
255
|
+
return withContexts();
|
|
256
|
+
}
|
|
257
|
+
const directory = ctx.get('workingDirectory');
|
|
258
|
+
const cwd = directory ? await directory.ensure(agent, signal) : agent.session.header.cwd ?? process.cwd();
|
|
259
|
+
const id = cavemanSessionId(String(agent.session.id));
|
|
260
|
+
const parent = agent.session.header.origin === 'subagent' && agent.session.header.parentSession
|
|
261
|
+
? cavemanSessionId(String(agent.session.header.parentSession)) : undefined;
|
|
262
|
+
const session = { caveman_session_id: id, host_session_id: id, cwd, ...(parent ? { parent_session_id: parent } : {}) };
|
|
263
|
+
const base = { protocol_version: 1, policy_mode: policy.mode, profile: policy.profile, agent: { id: 'dsh', surface: 'dsh' }, session,
|
|
264
|
+
model: { provider: modelSelection.provider, model: modelSelection.model } };
|
|
265
|
+
const current = sessions.get(agent);
|
|
266
|
+
if (!current || current.instance !== instance) {
|
|
267
|
+
const started = await nativeCall(home, { ...base, event: { type: 'session.start', timestamp_ms: Date.now() } }, signal);
|
|
268
|
+
const childStarted = parent ? await nativeCall(home, { ...base, event: { type: 'subagent.start', timestamp_ms: Date.now() } }, signal) : undefined;
|
|
269
|
+
sessions.set(agent, { instance, session, specialized, confirmed: Boolean(started || childStarted), contexts: [] });
|
|
270
|
+
owners.set(agent.session, agent);
|
|
271
|
+
}
|
|
272
|
+
for (const prompt of prompts) {
|
|
273
|
+
signal.throwIfAborted();
|
|
274
|
+
const response = await nativeCall(home, { ...base, event: { type: 'prompt.submit', timestamp_ms: Date.now() }, ...nativePrompt(prompt) }, signal);
|
|
275
|
+
if (!response)
|
|
276
|
+
break;
|
|
277
|
+
const state = sessions.get(agent);
|
|
278
|
+
if (state)
|
|
279
|
+
state.confirmed = true;
|
|
280
|
+
if (policy.core && !specialized && response.context && (!response.context.includes('ccr://') || await recoveryVisible()))
|
|
281
|
+
contexts.push(response.context);
|
|
282
|
+
}
|
|
283
|
+
return withContexts();
|
|
284
|
+
});
|
|
285
|
+
ctx.on('session/event', (session, event) => {
|
|
286
|
+
const kind = event.type;
|
|
287
|
+
if (kind !== 'compaction/start' && kind !== 'compaction/end')
|
|
288
|
+
return;
|
|
289
|
+
if (kind === 'compaction/end' && 'error' in event.data && event.data.error)
|
|
290
|
+
return;
|
|
291
|
+
const agent = owners.get(session);
|
|
292
|
+
const state = agent && sessions.get(agent);
|
|
293
|
+
if (!agent || !state)
|
|
294
|
+
return;
|
|
295
|
+
const task = (state.queue ?? Promise.resolve()).then(async () => {
|
|
296
|
+
if (sessions.get(agent) !== state || await runtimeInstance(endpoint, home) !== state.instance)
|
|
297
|
+
return;
|
|
298
|
+
const response = await nativeCall(home, { protocol_version: 1, policy_mode: policy.mode, profile: policy.profile,
|
|
299
|
+
agent: { id: 'dsh', surface: 'dsh' }, session: state.session,
|
|
300
|
+
event: { type: kind === 'compaction/start' ? 'context.compact.before' : 'context.compact.after', timestamp_ms: Date.now() } });
|
|
301
|
+
if (response)
|
|
302
|
+
state.confirmed = true;
|
|
303
|
+
if (kind === 'compaction/end' && response?.context)
|
|
304
|
+
state.contexts.push(response.context);
|
|
305
|
+
}).catch(() => { });
|
|
306
|
+
state.queue = task;
|
|
307
|
+
pending.add(task);
|
|
308
|
+
void task.finally(() => pending.delete(task));
|
|
309
|
+
});
|
|
310
|
+
ctx.on('tools/execute', async (exec, next) => {
|
|
311
|
+
if (!exec.agent || exec.name === 'run_code' || isManagedTool(exec.name))
|
|
312
|
+
return next();
|
|
313
|
+
const state = sessions.get(exec.agent);
|
|
314
|
+
if (!state?.confirmed)
|
|
315
|
+
return next();
|
|
316
|
+
if (await runtimeInstance(endpoint, home, exec.signal) !== state.instance) {
|
|
317
|
+
sessions.delete(exec.agent);
|
|
318
|
+
return next();
|
|
319
|
+
}
|
|
320
|
+
const base = { protocol_version: 1, policy_mode: policy.mode, profile: policy.profile, agent: { id: 'dsh', surface: 'dsh' }, session: state.session };
|
|
321
|
+
const beforeState = exec.name === 'read' ? await inputState(ctx, state.session.cwd, exec.arguments, exec.signal) : undefined;
|
|
322
|
+
const before = await nativeCall(home, { ...base, event: { type: 'tool.before', timestamp_ms: Date.now() },
|
|
323
|
+
tool: { name: exec.name, input: exec.arguments, ...(beforeState ? { input_state: beforeState } : {}) } }, exec.signal);
|
|
324
|
+
const result = await next();
|
|
325
|
+
let afterState;
|
|
326
|
+
if (!exec.signal.aborted && await runtimeInstance(endpoint, home, exec.signal) === state.instance) {
|
|
327
|
+
afterState = exec.name === 'read' ? await inputState(ctx, state.session.cwd, exec.arguments, exec.signal) : undefined;
|
|
328
|
+
const textOnly = result.content.every(block => block.type === 'text') && result.content.reduce((sum, block) => sum + (block.type === 'text' ? Buffer.byteLength(block.text, 'utf8') : 0), 0) <= 1_500_000;
|
|
329
|
+
const content = textOnly ? result.content.map(block => block.type === 'text' ? block.text : '').join('\n') : '';
|
|
330
|
+
await nativeCall(home, { ...base, event: { type: result.isError ? 'tool.failure' : 'tool.after', timestamp_ms: Date.now() },
|
|
331
|
+
tool: { name: exec.name, input: exec.arguments, ...(afterState ? { input_state: afterState } : {}), ...(content ? { output: Buffer.from(content).toString('base64') } : {}) } }, exec.signal);
|
|
332
|
+
}
|
|
333
|
+
const canRecover = exec.toolSet && ctx.tools.get('mcp__caveman__caveman_retrieve', exec.agent, exec.toolSet);
|
|
334
|
+
if (!policy.core || state.specialized || !before?.context || (before.context.includes('ccr://') && (!canRecover || !beforeState || beforeState !== afterState)) || exec.signal.aborted)
|
|
335
|
+
return result;
|
|
336
|
+
const reminder = createUserMessage({ source: { kind: 'dsh-caveman-native', form: 'notice' }, content: [{ type: 'text', text: before.context }] });
|
|
337
|
+
return { ...result, additionalContexts: [...result.additionalContexts ?? [], reminder] };
|
|
338
|
+
});
|
|
339
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
340
|
+
const state = sessions.get(agent);
|
|
341
|
+
if (!state)
|
|
342
|
+
return;
|
|
343
|
+
sessions.delete(agent);
|
|
344
|
+
const task = (state.queue ?? Promise.resolve()).then(async () => {
|
|
345
|
+
if (await runtimeInstance(endpoint, home) !== state.instance)
|
|
346
|
+
return;
|
|
347
|
+
const base = { protocol_version: 1, policy_mode: policy.mode, profile: policy.profile,
|
|
348
|
+
agent: { id: 'dsh', surface: 'dsh' }, session: state.session };
|
|
349
|
+
if (state.session.parent_session_id && !await nativeCall(home, { ...base, event: { type: 'subagent.stop', timestamp_ms: Date.now() } }))
|
|
350
|
+
return;
|
|
351
|
+
await nativeCall(home, { ...base, event: { type: 'session.end', timestamp_ms: Date.now() } });
|
|
352
|
+
});
|
|
353
|
+
pending.add(task);
|
|
354
|
+
void task.finally(() => pending.delete(task));
|
|
355
|
+
});
|
|
356
|
+
ctx.effect(() => async () => { await Promise.allSettled([...pending]); }, 'dsh-caveman:native');
|
|
357
|
+
}
|
package/lib/runtime.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { accessSync, constants, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { delimiter, isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
function executable(path) {
|
|
7
|
+
try {
|
|
8
|
+
accessSync(path, constants.X_OK);
|
|
9
|
+
return statSync(path).isFile();
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function pathCommand(name, env) {
|
|
16
|
+
const dirs = (env.PATH ?? env.Path ?? '').split(delimiter).filter(Boolean);
|
|
17
|
+
const names = process.platform === 'win32' && !name.toLowerCase().endsWith('.exe') ? [name, `${name}.exe`] : [name];
|
|
18
|
+
for (const dir of dirs)
|
|
19
|
+
for (const candidate of names) {
|
|
20
|
+
const path = resolve(dir, candidate);
|
|
21
|
+
if (executable(path))
|
|
22
|
+
return path;
|
|
23
|
+
}
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
/** Find a configured binary, PATH command, or the CLI's installation. */
|
|
27
|
+
export function findCavemanBinary(kind, configured, env = process.env) {
|
|
28
|
+
if (configured !== undefined) {
|
|
29
|
+
if (!isAbsolute(configured))
|
|
30
|
+
throw new Error(`dsh-caveman: ${kind}Binary must be an absolute path`);
|
|
31
|
+
return configured;
|
|
32
|
+
}
|
|
33
|
+
const override = env[{ blocks: 'CAVEMAN_BLOCKS_BIN', browse: 'CAVEMAN_BROWSE_BIN', mcp: 'CAVEMAN_MCP_BIN', memory: 'CAVEMEM_BIN' }[kind]];
|
|
34
|
+
if (override) {
|
|
35
|
+
if (isAbsolute(override) || /[\\/]/u.test(override)) {
|
|
36
|
+
const absolute = resolve(override);
|
|
37
|
+
return executable(absolute) ? absolute : undefined;
|
|
38
|
+
}
|
|
39
|
+
return pathCommand(override, env);
|
|
40
|
+
}
|
|
41
|
+
const name = kind === 'memory' ? 'cavemem' : `caveman-${kind}`;
|
|
42
|
+
const onPath = pathCommand(name, env);
|
|
43
|
+
if (onPath)
|
|
44
|
+
return onPath;
|
|
45
|
+
const filename = process.platform === 'win32' ? `${name}.exe` : name;
|
|
46
|
+
const local = resolve(env.CAVEMAN_HOME ?? join(homedir(), '.caveman'), 'bin', filename);
|
|
47
|
+
return executable(local) ? local : undefined;
|
|
48
|
+
}
|
|
49
|
+
function object(value) {
|
|
50
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
51
|
+
}
|
|
52
|
+
function configDocument(env) {
|
|
53
|
+
try {
|
|
54
|
+
const home = env.CAVEMAN_HOME ?? join(homedir(), '.caveman');
|
|
55
|
+
let raw;
|
|
56
|
+
try {
|
|
57
|
+
raw = readFileSync(join(home, 'cloud.json'), 'utf8');
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error.code !== 'ENOENT')
|
|
61
|
+
throw error;
|
|
62
|
+
raw = readFileSync(join(homedir(), '.caveman-cloud', 'config.json'), 'utf8');
|
|
63
|
+
}
|
|
64
|
+
return object(JSON.parse(raw.replace(/^\uFEFF/u, '')));
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return {};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function booleanSetting(value) {
|
|
71
|
+
if (typeof value === 'boolean')
|
|
72
|
+
return value;
|
|
73
|
+
if (typeof value !== 'string')
|
|
74
|
+
return undefined;
|
|
75
|
+
const normalized = value.trim().toLowerCase();
|
|
76
|
+
if (['1', 'true', 'yes', 'on'].includes(normalized))
|
|
77
|
+
return true;
|
|
78
|
+
if (['0', 'false', 'no', 'off'].includes(normalized))
|
|
79
|
+
return false;
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
/** Read the module switches and native coding policy in one configuration snapshot. */
|
|
83
|
+
export function runtimeSettings(env = process.env) {
|
|
84
|
+
const document = configDocument(env);
|
|
85
|
+
const modules = object(document.modules);
|
|
86
|
+
const think = object(document.think);
|
|
87
|
+
const wrap = object(document.wrap);
|
|
88
|
+
const explicit = (value) => typeof value === 'boolean' ? value : undefined;
|
|
89
|
+
const input = explicit(modules.input) ?? ((think.mode ?? wrap.mode) !== 'record');
|
|
90
|
+
const scripts = explicit(modules.scripts) ?? true;
|
|
91
|
+
const browse = explicit(modules.browse) ?? booleanSetting(object(document.execute).browse_tool ?? wrap.browse) ?? true;
|
|
92
|
+
const mcpMode = env.CAVEMAN_MCP ?? object(document.execute).mcp ?? wrap.mcp;
|
|
93
|
+
const mcp = mcpMode !== 'marker-only' && booleanSetting(mcpMode) !== false;
|
|
94
|
+
const memory = booleanSetting(object(document.remember).mem) ?? true;
|
|
95
|
+
const configuredCore = booleanSetting(env.CAVEMAN_CORE) ?? booleanSetting(think.core ?? wrap.core) ?? explicit(modules.output) ?? true;
|
|
96
|
+
const profile = env.CAVEMAN_NATIVE_PROFILE?.trim().toLowerCase();
|
|
97
|
+
const profiles = ['record-only', 'core', 'core-lean-build', 'ledger', 'ccr-masking', 'cache-aware', 'full-safe', 'full-max'];
|
|
98
|
+
const configuredMode = env.CAVEMAN_NATIVE_MODE?.trim().toLowerCase();
|
|
99
|
+
const proxyMode = env.CAVEMAN_WRAP_MODE ?? think.mode ?? wrap.mode ?? 'compress';
|
|
100
|
+
const nativeMode = profile && !profiles.includes(profile) || profile === 'record-only'
|
|
101
|
+
? 'record'
|
|
102
|
+
: configuredMode ? configuredMode === 'safe' || configuredMode === 'max' ? configuredMode : 'record'
|
|
103
|
+
: proxyMode === 'record' ? 'record' : proxyMode === 'pixel' ? 'max' : 'safe';
|
|
104
|
+
const nativeProfile = profile && profiles.includes(profile) ? profile : nativeMode === 'record' ? 'record-only' : nativeMode === 'max' ? 'full-max' : 'full-safe';
|
|
105
|
+
const core = configuredCore && nativeMode !== 'record' && nativeProfile !== 'record-only';
|
|
106
|
+
return { input, scripts, browse, mcp, memory, core, coreLeanBuild: core && nativeProfile === 'core-lean-build', nativeMode, nativeProfile };
|
|
107
|
+
}
|
|
108
|
+
/** Modules default to on; a saved explicit off is respected. */
|
|
109
|
+
export function moduleEnabled(kind, env = process.env) {
|
|
110
|
+
return runtimeSettings(env)[kind];
|
|
111
|
+
}
|
|
112
|
+
function localOrigin(endpoint) {
|
|
113
|
+
try {
|
|
114
|
+
const url = new URL(endpoint);
|
|
115
|
+
if (url.protocol !== 'http:' || url.username || url.password || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
116
|
+
return undefined;
|
|
117
|
+
return url;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// Use an explicit direct connection, even when the host process uses an HTTP proxy.
|
|
124
|
+
async function directLocalFetch(input, init) {
|
|
125
|
+
const request = new Request(input, init);
|
|
126
|
+
const url = localOrigin(request.url);
|
|
127
|
+
if (!url)
|
|
128
|
+
throw new Error('Caveman runtime must use a loopback HTTP address');
|
|
129
|
+
const body = request.body === null ? undefined : Buffer.from(await request.arrayBuffer());
|
|
130
|
+
return new Promise((resolveResponse, reject) => {
|
|
131
|
+
const child = httpRequest({
|
|
132
|
+
hostname: url.hostname === 'localhost' ? '127.0.0.1' : url.hostname.replace(/^\[|\]$/gu, ''),
|
|
133
|
+
port: url.port || 80, path: `${url.pathname}${url.search}`, method: request.method,
|
|
134
|
+
headers: Object.fromEntries(request.headers), signal: request.signal, agent: false,
|
|
135
|
+
}, response => {
|
|
136
|
+
try {
|
|
137
|
+
const status = response.statusCode ?? 500;
|
|
138
|
+
const headers = new Headers();
|
|
139
|
+
for (const [name, value] of Object.entries(response.headers)) {
|
|
140
|
+
if (Array.isArray(value))
|
|
141
|
+
for (const item of value)
|
|
142
|
+
headers.append(name, item);
|
|
143
|
+
else if (value !== undefined)
|
|
144
|
+
headers.set(name, value);
|
|
145
|
+
}
|
|
146
|
+
const empty = status === 204 || status === 205 || status === 304;
|
|
147
|
+
if (empty)
|
|
148
|
+
response.resume();
|
|
149
|
+
const stream = empty ? null : Readable.toWeb(response);
|
|
150
|
+
resolveResponse(new Response(stream, { status, statusText: response.statusMessage, headers }));
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
response.destroy();
|
|
154
|
+
reject(error);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
child.once('error', reject);
|
|
158
|
+
child.end(body);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** Verify that the loopback listener matches the runtime's private run-state record. */
|
|
162
|
+
export async function verifiedRuntime(endpoint, env = process.env, signal) {
|
|
163
|
+
signal?.throwIfAborted();
|
|
164
|
+
const url = localOrigin(endpoint);
|
|
165
|
+
if (!url)
|
|
166
|
+
return false;
|
|
167
|
+
const port = Number(url.port || 80);
|
|
168
|
+
try {
|
|
169
|
+
const home = env.CAVEMAN_HOME ?? join(homedir(), '.caveman');
|
|
170
|
+
const state = JSON.parse(readFileSync(join(home, 'run', `${port}.json`), 'utf8'));
|
|
171
|
+
if (!state || typeof state !== 'object' || Array.isArray(state))
|
|
172
|
+
return false;
|
|
173
|
+
const run = state;
|
|
174
|
+
if (run.schema !== 'caveman.proxy.run.v1' || (run.owner !== 'start' && run.owner !== 'wrap') ||
|
|
175
|
+
typeof run.pid !== 'number' || run.port !== port || typeof run.instance_token !== 'string' || !run.instance_token)
|
|
176
|
+
return false;
|
|
177
|
+
const timeout = AbortSignal.timeout(750);
|
|
178
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
179
|
+
const health = await directLocalFetch(`${url.origin}/health/live`, { signal: combined });
|
|
180
|
+
const matches = health.ok && health.headers.get('x-caveman-instance') === run.instance_token;
|
|
181
|
+
await health.body?.cancel();
|
|
182
|
+
return matches;
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
signal?.throwIfAborted();
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Guard every automatic middleware call against a different or replaced listener. */
|
|
190
|
+
export function guardedRuntimeFetch(endpoint, env = process.env) {
|
|
191
|
+
const origin = localOrigin(endpoint)?.origin;
|
|
192
|
+
return async (input, init) => {
|
|
193
|
+
const request = new Request(input, init);
|
|
194
|
+
if (!origin || localOrigin(request.url)?.origin !== origin || !await verifiedRuntime(endpoint, env, request.signal)) {
|
|
195
|
+
throw new Error('Caveman runtime is unavailable or unverified');
|
|
196
|
+
}
|
|
197
|
+
return directLocalFetch(request);
|
|
198
|
+
};
|
|
199
|
+
}
|
package/lib/skills.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, join, sep } from 'node:path';
|
|
3
|
+
import { parse as parseYaml } from 'yaml';
|
|
4
|
+
const PROVIDER = 'dsh-caveman';
|
|
5
|
+
const RANK = 600;
|
|
6
|
+
const NAMES = [
|
|
7
|
+
'caveman', 'ultracave', 'megacave', 'caveman-help',
|
|
8
|
+
'caveman-commit', 'caveman-review', 'caveman-compress', 'caveman-stats',
|
|
9
|
+
'cavecrew', 'caveman-discover', 'caveman-explore', 'caveman-learn',
|
|
10
|
+
'caveman-manage', 'caveman-optimize', 'caveman-evidence-review', 'caveman-setup',
|
|
11
|
+
'investigate-first', 'lean-build', 'migration', 'safe-refactor', 'surgical-patch', 'verify-and-stop',
|
|
12
|
+
];
|
|
13
|
+
const knownNames = new Set(NAMES);
|
|
14
|
+
async function readSkill(root, name, signal) {
|
|
15
|
+
const path = join(root, name, 'SKILL.md');
|
|
16
|
+
const raw = await readFile(path, { encoding: 'utf8', signal });
|
|
17
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(raw);
|
|
18
|
+
if (!frontmatter?.[1])
|
|
19
|
+
throw new Error(`dsh-caveman: missing skill metadata in ${path}`);
|
|
20
|
+
const metadata = parseYaml(frontmatter[1]);
|
|
21
|
+
const description = typeof metadata === 'object' && metadata !== null && 'description' in metadata
|
|
22
|
+
? metadata.description : undefined;
|
|
23
|
+
if (typeof description !== 'string' || !description.trim()) {
|
|
24
|
+
throw new Error(`dsh-caveman: missing skill description in ${path}`);
|
|
25
|
+
}
|
|
26
|
+
const fields = metadata;
|
|
27
|
+
return {
|
|
28
|
+
description: description.trim().replace(/\s+/g, ' '), content: raw.slice(frontmatter[0].length).trim(),
|
|
29
|
+
modelInvocable: fields['disable-model-invocation'] !== true,
|
|
30
|
+
userInvocable: fields['user-invocable'] !== false,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Expose skills through the DSH provider registry. */
|
|
34
|
+
export function createSkillProvider(root, control) {
|
|
35
|
+
if (!isAbsolute(root))
|
|
36
|
+
throw new Error('dsh-caveman: skill root must be absolute');
|
|
37
|
+
return {
|
|
38
|
+
name: PROVIDER,
|
|
39
|
+
async list({ signal }) {
|
|
40
|
+
const results = await Promise.allSettled(NAMES.map(async (name) => {
|
|
41
|
+
const { description, modelInvocable, userInvocable } = await readSkill(root, name, signal);
|
|
42
|
+
const directory = join(root, name);
|
|
43
|
+
return {
|
|
44
|
+
name, description, source: 'bundled', provider: PROVIDER,
|
|
45
|
+
invocation: { modelInvocable, userInvocable },
|
|
46
|
+
rank: RANK, locator: name,
|
|
47
|
+
resourceBase: { kind: 'directory', path: directory.split(sep).join('/') },
|
|
48
|
+
};
|
|
49
|
+
}));
|
|
50
|
+
signal?.throwIfAborted();
|
|
51
|
+
return {
|
|
52
|
+
candidates: results.flatMap(result => result.status === 'fulfilled' ? [result.value] : []),
|
|
53
|
+
complete: results.every(result => result.status === 'fulfilled'),
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
async get(candidate, { signal }) {
|
|
57
|
+
if (!knownNames.has(candidate.name) || candidate.locator !== candidate.name)
|
|
58
|
+
return undefined;
|
|
59
|
+
try {
|
|
60
|
+
const { content } = await readSkill(root, candidate.name, signal);
|
|
61
|
+
const { rank: _rank, locator: _locator, ...summary } = candidate;
|
|
62
|
+
return { ...summary, content };
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (signal?.aborted)
|
|
66
|
+
throw error;
|
|
67
|
+
if (typeof error === 'object' && error !== null && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) {
|
|
68
|
+
control?.invalidate();
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|