@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
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { freezeMessage } from '@deepseek-ai/dsh-llm';
|
|
5
|
+
import { MiddlewareRuntime, recoveryToolDescription } from '@caveman-ai/sdk/middleware';
|
|
6
|
+
const HANDLE = /^cmw_[a-f0-9]{48}$/u;
|
|
7
|
+
const MARKER = /\[caveman: shortened; exact original via caveman_retrieve handle=(cmw_[a-f0-9]{48})/u;
|
|
8
|
+
const MINIMUM_TEXT_LENGTH = 2048;
|
|
9
|
+
const packageVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
10
|
+
const ADAPTER = { id: 'dsh', version: packageVersion, framework_version: 'unknown', serialization_revision: 'dsh-session-v1' };
|
|
11
|
+
// DSH's supported schema subset omits numeric and regex constraints. Enforce
|
|
12
|
+
// those constraints in parseArgs while exposing a usable SDK declaration.
|
|
13
|
+
const RECOVERY_PARAMETERS = {
|
|
14
|
+
type: 'object', additionalProperties: false, required: ['handle'],
|
|
15
|
+
properties: { handle: { type: 'string' }, offset: { type: 'integer' }, limit: { type: 'integer' }, query: { type: 'string' } },
|
|
16
|
+
};
|
|
17
|
+
function scopeFor(agent) {
|
|
18
|
+
return { namespace: 'dsh-caveman', session_id: String(agent.session.id), branch_id: 'main', cache_epoch: '0' };
|
|
19
|
+
}
|
|
20
|
+
function parseArgs(value) {
|
|
21
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
22
|
+
throw new Error('Invalid recovery arguments');
|
|
23
|
+
const args = value;
|
|
24
|
+
if (Object.keys(args).some(key => !['handle', 'offset', 'limit', 'query'].includes(key)) ||
|
|
25
|
+
typeof args.handle !== 'string' || !HANDLE.test(args.handle) ||
|
|
26
|
+
(args.offset !== undefined && (!Number.isSafeInteger(args.offset) || args.offset < 0)) ||
|
|
27
|
+
(args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 4 || args.limit > 262144)) ||
|
|
28
|
+
(args.query !== undefined && (typeof args.query !== 'string' || args.query.length > 1024))) {
|
|
29
|
+
throw new Error('Invalid recovery arguments');
|
|
30
|
+
}
|
|
31
|
+
return args;
|
|
32
|
+
}
|
|
33
|
+
function textBlocks(event) {
|
|
34
|
+
if (event.type !== 'tool/result' || event.data.message.isError)
|
|
35
|
+
return [];
|
|
36
|
+
return event.data.message.content.flatMap((block, index) => block.type === 'text' ? [{ index, text: block.text }] : []);
|
|
37
|
+
}
|
|
38
|
+
export function isManagedTool(name) {
|
|
39
|
+
return name === 'caveman_retrieve' || name === 'cavemem_recover' || name.startsWith('mcp__caveman__') || name.startsWith('mcp__caveman_browse__') || name.startsWith('mcp__cavemem__') ||
|
|
40
|
+
/^mcp__.+__(?:caveman_retrieve|browser_recover)$/u.test(name);
|
|
41
|
+
}
|
|
42
|
+
/** Index immutable history once per session instead of rescanning it on every step. */
|
|
43
|
+
export class CompressionHistoryIndex {
|
|
44
|
+
states = new WeakMap();
|
|
45
|
+
read(session) {
|
|
46
|
+
const end = session.seq;
|
|
47
|
+
const previous = this.states.get(session);
|
|
48
|
+
const state = previous && previous.seq <= end ? previous : {
|
|
49
|
+
seq: 0, toolNames: new Map(), managedCalls: new Set(), hasMarker: false, originals: new Map(),
|
|
50
|
+
};
|
|
51
|
+
for (const event of session.snapshotEvents(state.seq, end)) {
|
|
52
|
+
const dispatch = event;
|
|
53
|
+
if (dispatch.type === 'tool/ptc-dispatch' && typeof dispatch.data.rootCallId === 'string' &&
|
|
54
|
+
typeof dispatch.data.name === 'string' && isManagedTool(dispatch.data.name))
|
|
55
|
+
state.managedCalls.add(dispatch.data.rootCallId);
|
|
56
|
+
if (event.type === 'assistant/message') {
|
|
57
|
+
for (const block of event.data.message.content) {
|
|
58
|
+
if (block.type === 'tool-call' && !state.toolNames.has(block.id))
|
|
59
|
+
state.toolNames.set(block.id, block.name);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
for (const block of textBlocks(event)) {
|
|
63
|
+
const handle = MARKER.exec(block.text)?.[1];
|
|
64
|
+
if (!handle)
|
|
65
|
+
continue;
|
|
66
|
+
state.hasMarker = true;
|
|
67
|
+
if (state.originals.has(handle) || event.sourceEventSeqs?.length !== 1)
|
|
68
|
+
continue;
|
|
69
|
+
const source = session.eventAt(event.sourceEventSeqs[0]);
|
|
70
|
+
const original = source && textBlocks(source).find(candidate => candidate.index === block.index);
|
|
71
|
+
if (source?.type === 'tool/result' && original) {
|
|
72
|
+
state.originals.set(handle, { text: original.text, sourceId: `seq-${resolveOriginalResult(session, source).seq}` });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
state.seq = end;
|
|
77
|
+
this.states.set(session, state);
|
|
78
|
+
return state;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function fallbackPage(history, session, args) {
|
|
82
|
+
if (args.query !== undefined)
|
|
83
|
+
return undefined;
|
|
84
|
+
const original = history.read(session).originals.get(args.handle);
|
|
85
|
+
if (!original)
|
|
86
|
+
return undefined;
|
|
87
|
+
const bytes = Buffer.from(original.text, 'utf8');
|
|
88
|
+
const offset = args.offset ?? 0;
|
|
89
|
+
if (offset > bytes.length)
|
|
90
|
+
throw new Error('Recovery offset exceeds the original length');
|
|
91
|
+
let end = Math.min(offset + (args.limit ?? 262144), bytes.length);
|
|
92
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
93
|
+
let page;
|
|
94
|
+
for (let attempt = 0; attempt < 4 && end >= offset; attempt++, end--) {
|
|
95
|
+
try {
|
|
96
|
+
page = decoder.decode(bytes.subarray(offset, end));
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
catch { }
|
|
100
|
+
}
|
|
101
|
+
if (page === undefined)
|
|
102
|
+
throw new Error('Recovery offset is not a UTF-8 boundary');
|
|
103
|
+
const actualEnd = offset + Buffer.byteLength(page);
|
|
104
|
+
return JSON.stringify({
|
|
105
|
+
schema_version: 1, handle: args.handle, source_id: original.sourceId, text: page,
|
|
106
|
+
original_sha256: createHash('sha256').update(bytes).digest('hex'), total_bytes: bytes.length,
|
|
107
|
+
complete: offset === 0 && actualEnd === bytes.length, kind: 'original_page', offset,
|
|
108
|
+
next_offset: actualEnd === bytes.length ? null : actualEnd,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const resultOrigins = new WeakMap();
|
|
112
|
+
/** Resolve immutable event ancestry once per session, reusing earlier results. */
|
|
113
|
+
export function resolveOriginalResult(session, event) {
|
|
114
|
+
const cache = resultOrigins.get(session) ?? new WeakMap();
|
|
115
|
+
resultOrigins.set(session, cache);
|
|
116
|
+
const visited = [];
|
|
117
|
+
let current = event;
|
|
118
|
+
for (;;) {
|
|
119
|
+
const known = cache.get(current);
|
|
120
|
+
if (known) {
|
|
121
|
+
current = known;
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
visited.push(current);
|
|
125
|
+
const previous = (current.sourceEventSeqs ?? []).map(seq => session.eventAt(seq))
|
|
126
|
+
.filter((item) => item?.type === 'tool/result');
|
|
127
|
+
if (!previous.length)
|
|
128
|
+
break;
|
|
129
|
+
const oldest = previous.reduce((a, b) => a.seq < b.seq ? a : b);
|
|
130
|
+
if (oldest.seq >= current.seq)
|
|
131
|
+
break;
|
|
132
|
+
current = oldest;
|
|
133
|
+
}
|
|
134
|
+
for (const item of visited)
|
|
135
|
+
cache.set(item, current);
|
|
136
|
+
return current;
|
|
137
|
+
}
|
|
138
|
+
function manifestFor(session) {
|
|
139
|
+
return session.surface.nodes.map(seq => {
|
|
140
|
+
let event = session.eventAt(seq);
|
|
141
|
+
if (event.type === 'tool/result')
|
|
142
|
+
event = resolveOriginalResult(session, event);
|
|
143
|
+
const data = event.type === 'user/message' ? event.data : 'message' in event.data ? event.data.message : event.data;
|
|
144
|
+
return { id: `seq-${event.seq}`, sha256: createHash('sha256').update(JSON.stringify(data)).digest('hex') };
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function surfaceMatchesManifest(session, manifest) {
|
|
148
|
+
if (session.surface.nodes.length !== manifest.length)
|
|
149
|
+
return false;
|
|
150
|
+
return session.surface.nodes.every((seq, index) => {
|
|
151
|
+
let event = session.eventAt(seq);
|
|
152
|
+
if (!event)
|
|
153
|
+
return false;
|
|
154
|
+
if (event.type === 'tool/result')
|
|
155
|
+
event = resolveOriginalResult(session, event);
|
|
156
|
+
return manifest[index]?.id === `seq-${event.seq}`;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/** Check the changed blocks on each matching tool result, including partial projections. */
|
|
160
|
+
export function projectionCoverage(expected, messages) {
|
|
161
|
+
const projections = expected.map(item => {
|
|
162
|
+
const target = messages.find(message => message.role === 'tool' && message.toolCallId === item.callId);
|
|
163
|
+
return target ? item.blocks.every(({ index, text }) => {
|
|
164
|
+
const block = target.content[index];
|
|
165
|
+
return block?.type === 'text' && block.text === text;
|
|
166
|
+
}) : undefined;
|
|
167
|
+
});
|
|
168
|
+
if (projections.every(value => value === undefined))
|
|
169
|
+
return 'none';
|
|
170
|
+
return projections.every(value => value === true) ? 'complete' : 'incomplete';
|
|
171
|
+
}
|
|
172
|
+
/** Keep each result together while respecting middleware limits and unique segment ids. */
|
|
173
|
+
export function planCompressionBatches(items, byteBudget, maxSegments) {
|
|
174
|
+
const batches = [];
|
|
175
|
+
let batch = [];
|
|
176
|
+
let bytes = 0;
|
|
177
|
+
let count = 0;
|
|
178
|
+
let ids = new Set();
|
|
179
|
+
for (const item of items) {
|
|
180
|
+
if (batch.length && (bytes + item.bytes > byteBudget || count + item.segments.length > maxSegments || item.segments.some(segment => ids.has(segment.id)))) {
|
|
181
|
+
batches.push(batch);
|
|
182
|
+
batch = [];
|
|
183
|
+
bytes = 0;
|
|
184
|
+
count = 0;
|
|
185
|
+
ids = new Set();
|
|
186
|
+
}
|
|
187
|
+
batch.push(item);
|
|
188
|
+
bytes += item.bytes;
|
|
189
|
+
count += item.segments.length;
|
|
190
|
+
for (const segment of item.segments)
|
|
191
|
+
ids.add(segment.id);
|
|
192
|
+
}
|
|
193
|
+
if (batch.length)
|
|
194
|
+
batches.push(batch);
|
|
195
|
+
return batches;
|
|
196
|
+
}
|
|
197
|
+
/** Only shorten a result when the actual assembly exposes recovery to the model. */
|
|
198
|
+
function recoveryExposure(assembly, tool) {
|
|
199
|
+
const direct = assembly.tools.find(entry => entry.name === tool.name);
|
|
200
|
+
if (direct && direct.description === tool.description && isDeepStrictEqual(direct.parameters, tool.parameters))
|
|
201
|
+
return { kind: 'direct' };
|
|
202
|
+
const transport = assembly.tools.find(entry => entry.name === 'run_code');
|
|
203
|
+
const section = assembly.sections.find(entry => entry.name === 'tools:sdk' && entry.interpolate === false);
|
|
204
|
+
if (!transport || !section || !section.text.includes(tool.description))
|
|
205
|
+
return undefined;
|
|
206
|
+
const sdk = section.text;
|
|
207
|
+
const typescript = /(?:^|\n) caveman_retrieve: \{\n handle: string;\n offset\?: number;\n limit\?: number;\n query\?: string;\n \};(?:\n|$)/u.test(sdk) &&
|
|
208
|
+
/interface ToolOutputMap \{[\s\S]*?\n caveman_retrieve: string;/u.test(sdk);
|
|
209
|
+
const python = /class (\w+)\(TypedDict\):\n handle: str\n offset: NotRequired\[int\]\n limit: NotRequired\[int\]\n query: NotRequired\[str\]/u.exec(sdk);
|
|
210
|
+
if (!typescript && !(python && sdk.includes(`async def caveman_retrieve(self, args: ${python[1]}) -> str:`)))
|
|
211
|
+
return undefined;
|
|
212
|
+
return { kind: 'program', sdk, transport };
|
|
213
|
+
}
|
|
214
|
+
/** Install recoverable compression using the middleware protocol. */
|
|
215
|
+
export function registerCompression(ctx, endpoint, automatic) {
|
|
216
|
+
const runtime = new MiddlewareRuntime({ endpoint, mode: 'compress', ...(automatic ? { fetch: automatic.fetch } : {}) });
|
|
217
|
+
const history = new CompressionHistoryIndex();
|
|
218
|
+
const pending = new Map();
|
|
219
|
+
function restore(session) {
|
|
220
|
+
const key = String(session.id);
|
|
221
|
+
const work = pending.get(key);
|
|
222
|
+
if (!work || work.session !== session)
|
|
223
|
+
return [];
|
|
224
|
+
while (work.replacements.length) {
|
|
225
|
+
const replacement = work.replacements[0];
|
|
226
|
+
if (session.surface.nodes.includes(replacement.seq)) {
|
|
227
|
+
session.append('tool/result', replacement.original.data, {
|
|
228
|
+
surfaceOp: { op: 'replace', startSeq: replacement.seq, endSeq: replacement.seq },
|
|
229
|
+
sourceEventSeqs: [replacement.seq, replacement.original.seq],
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
else
|
|
233
|
+
work.optimizations.set(replacement.optimization, false);
|
|
234
|
+
// Retain the current item until append succeeds so idle/disposal can
|
|
235
|
+
// retry a transient restoration error without stranding the projection.
|
|
236
|
+
work.replacements.shift();
|
|
237
|
+
}
|
|
238
|
+
pending.delete(key);
|
|
239
|
+
return [...work.optimizations].filter(([, applied]) => applied).map(([optimization]) => optimization);
|
|
240
|
+
}
|
|
241
|
+
const tool = {
|
|
242
|
+
name: 'caveman_retrieve', description: `${recoveryToolDescription} Offset must be nonnegative; limit must be 4–262144 bytes; query must be at most 1024 characters.`,
|
|
243
|
+
parameters: structuredClone(RECOVERY_PARAMETERS),
|
|
244
|
+
output: {
|
|
245
|
+
schema: { type: 'string' },
|
|
246
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
247
|
+
},
|
|
248
|
+
async execute(value, exec) {
|
|
249
|
+
if (!exec.agent)
|
|
250
|
+
throw new Error('Caveman recovery requires an agent session');
|
|
251
|
+
const args = parseArgs(value);
|
|
252
|
+
try {
|
|
253
|
+
return JSON.stringify(await runtime.retrieve(scopeFor(exec.agent), args, exec.signal));
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
exec.signal.throwIfAborted();
|
|
257
|
+
const fallback = fallbackPage(history, exec.agent.session, args);
|
|
258
|
+
if (fallback !== undefined)
|
|
259
|
+
return fallback;
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
if (ctx.tools.get(tool.name)) {
|
|
265
|
+
ctx.logger.warn('dsh-caveman: recovery tool name is already in use; input compression is disabled');
|
|
266
|
+
runtime.close();
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
ctx.tools.register(tool, automatic ? {
|
|
270
|
+
when: ({ agent, signal }) => history.read(agent.session).hasMarker || automatic.available(signal),
|
|
271
|
+
} : undefined);
|
|
272
|
+
ctx.effect(() => () => {
|
|
273
|
+
try {
|
|
274
|
+
for (const work of [...pending.values()])
|
|
275
|
+
restore(work.session);
|
|
276
|
+
}
|
|
277
|
+
finally {
|
|
278
|
+
runtime.close();
|
|
279
|
+
}
|
|
280
|
+
}, 'dsh-caveman:runtime');
|
|
281
|
+
ctx.on('agent/status', ({ agent, status }) => {
|
|
282
|
+
if (status === 'idle' && pending.has(String(agent.session.id)))
|
|
283
|
+
restore(agent.session);
|
|
284
|
+
});
|
|
285
|
+
ctx.on('llm/stream', (options, next) => (async function* () {
|
|
286
|
+
const work = options.sessionId === undefined ? undefined : pending.get(String(options.sessionId));
|
|
287
|
+
if (work) {
|
|
288
|
+
const coverage = projectionCoverage(work.replacements.map(replacement => ({
|
|
289
|
+
callId: replacement.original.data.message.toolCallId, blocks: replacement.sentBlocks,
|
|
290
|
+
})), options.messages);
|
|
291
|
+
const visible = options.tools?.find(entry => entry.name === (work.exposure.kind === 'direct' ? tool.name : 'run_code'));
|
|
292
|
+
const lastSystem = options.messages.filter(message => message.role === 'system' && message.content.some(block => block.type === 'text' && block.text)).at(-1);
|
|
293
|
+
const systemText = lastSystem?.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
|
|
294
|
+
const valid = work.exposure.kind === 'direct'
|
|
295
|
+
? visible && visible.description === tool.description && isDeepStrictEqual(visible.parameters, tool.parameters)
|
|
296
|
+
: visible && isDeepStrictEqual(visible, work.exposure.transport) && systemText?.includes(work.exposure.sdk);
|
|
297
|
+
const restored = restore(work.session);
|
|
298
|
+
if (coverage !== 'none' && (coverage !== 'complete' || !valid)) {
|
|
299
|
+
throw new Error('dsh-caveman: compressed results or their recovery tool were not available for the request');
|
|
300
|
+
}
|
|
301
|
+
if (coverage === 'complete')
|
|
302
|
+
for (const optimization of restored)
|
|
303
|
+
runtime.report(optimization);
|
|
304
|
+
}
|
|
305
|
+
yield* next();
|
|
306
|
+
})());
|
|
307
|
+
const selections = new WeakMap();
|
|
308
|
+
ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
|
309
|
+
const result = await next();
|
|
310
|
+
if (context.agent && context.toolSet)
|
|
311
|
+
selections.set(context.agent, context.toolSet);
|
|
312
|
+
return result;
|
|
313
|
+
});
|
|
314
|
+
ctx.on('agent/pre-step', async ({ agent, modelSelection, signal }, next) => {
|
|
315
|
+
const decision = await next();
|
|
316
|
+
if (decision.kind === 'reject')
|
|
317
|
+
return decision;
|
|
318
|
+
const toolSet = selections.get(agent);
|
|
319
|
+
if (!toolSet || ctx.tools.get(tool.name, agent, toolSet) !== tool)
|
|
320
|
+
return decision;
|
|
321
|
+
const session = agent.session;
|
|
322
|
+
if (pending.has(String(session.id)))
|
|
323
|
+
restore(session);
|
|
324
|
+
const { toolNames, managedCalls } = history.read(session);
|
|
325
|
+
const eligible = [];
|
|
326
|
+
for (const seq of [...session.surface.nodes]) {
|
|
327
|
+
const event = session.eventAt(seq);
|
|
328
|
+
if (!event || event.type !== 'tool/result')
|
|
329
|
+
continue;
|
|
330
|
+
const blocks = textBlocks(event).filter(block => block.text.length >= MINIMUM_TEXT_LENGTH && !MARKER.test(block.text));
|
|
331
|
+
if (!blocks.length)
|
|
332
|
+
continue;
|
|
333
|
+
const toolName = toolNames.get(event.data.message.toolCallId);
|
|
334
|
+
if (!toolName || isManagedTool(toolName) || managedCalls.has(event.data.message.toolCallId))
|
|
335
|
+
continue;
|
|
336
|
+
eligible.push({ seq, event, blocks });
|
|
337
|
+
}
|
|
338
|
+
if (!eligible.length)
|
|
339
|
+
return decision;
|
|
340
|
+
const assembly = await ctx.systemPrompt.assemble({ scope: agent, agent, modelSelection, toolSet, signal });
|
|
341
|
+
const exposure = recoveryExposure(assembly, tool);
|
|
342
|
+
if (!exposure)
|
|
343
|
+
return decision;
|
|
344
|
+
const published = { name: tool.name, description: tool.description, parameters: tool.parameters };
|
|
345
|
+
const scope = scopeFor(agent);
|
|
346
|
+
const binding = runtime.recovery(scope);
|
|
347
|
+
if (!binding)
|
|
348
|
+
return decision;
|
|
349
|
+
let capabilities;
|
|
350
|
+
try {
|
|
351
|
+
capabilities = await runtime.ready(signal);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
signal.throwIfAborted();
|
|
355
|
+
return decision;
|
|
356
|
+
}
|
|
357
|
+
const manifest = manifestFor(session);
|
|
358
|
+
const maxSegments = capabilities.limits.max_segments ?? 256;
|
|
359
|
+
const byteBudget = Math.max(0, capabilities.limits.request_bytes - Buffer.byteLength(JSON.stringify(manifest), 'utf8') - 16_384);
|
|
360
|
+
const prepared = eligible.map(candidate => {
|
|
361
|
+
const sourceId = `seq-${resolveOriginalResult(session, candidate.event).seq}`;
|
|
362
|
+
const segments = candidate.blocks.map(block => ({
|
|
363
|
+
id: candidate.event.data.message.content.length === 1 ? sourceId : `${sourceId}-block-${block.index}`,
|
|
364
|
+
sourceId, kind: 'tool_result', content: block.text, index: block.index,
|
|
365
|
+
}));
|
|
366
|
+
return { ...candidate, sourceId, segments, bytes: segments.reduce((sum, segment) => sum + Buffer.byteLength(JSON.stringify(segment), 'utf8') + 256, 0) };
|
|
367
|
+
});
|
|
368
|
+
const batches = planCompressionBatches(prepared, byteBudget, maxSegments);
|
|
369
|
+
try {
|
|
370
|
+
for (const group of batches) {
|
|
371
|
+
signal.throwIfAborted();
|
|
372
|
+
if (!surfaceMatchesManifest(session, manifest)) {
|
|
373
|
+
restore(session);
|
|
374
|
+
return decision;
|
|
375
|
+
}
|
|
376
|
+
const candidates = group.filter(candidate => session.surface.nodes.includes(candidate.seq));
|
|
377
|
+
if (!candidates.length || ctx.tools.get(tool.name, agent, toolSet) !== tool)
|
|
378
|
+
continue;
|
|
379
|
+
const segments = candidates.flatMap(candidate => candidate.segments);
|
|
380
|
+
const optimization = await runtime.optimize({
|
|
381
|
+
scope, binding, adapter: ADAPTER, manifest,
|
|
382
|
+
candidates: segments,
|
|
383
|
+
model: { provider: modelSelection.provider, id: modelSelection.model, protocol: 'dsh' },
|
|
384
|
+
recoveryOverheadText: JSON.stringify(published), signal,
|
|
385
|
+
});
|
|
386
|
+
signal.throwIfAborted();
|
|
387
|
+
if (!surfaceMatchesManifest(session, manifest) || ctx.tools.get(tool.name, agent, toolSet) !== tool) {
|
|
388
|
+
restore(session);
|
|
389
|
+
return decision;
|
|
390
|
+
}
|
|
391
|
+
if (!optimization.replacements.length)
|
|
392
|
+
continue;
|
|
393
|
+
const updates = new Map();
|
|
394
|
+
let invalid = false;
|
|
395
|
+
for (const replacement of optimization.replacements) {
|
|
396
|
+
const candidate = candidates.find(item => item.segments.some(segment => segment.id === replacement.segment_id));
|
|
397
|
+
const segment = candidate?.segments.find(item => item.id === replacement.segment_id);
|
|
398
|
+
if (!candidate || !segment || replacement.source_id !== candidate.sourceId || !session.surface.nodes.includes(candidate.seq)) {
|
|
399
|
+
invalid = true;
|
|
400
|
+
break;
|
|
401
|
+
}
|
|
402
|
+
const changes = updates.get(candidate) ?? new Map();
|
|
403
|
+
if (changes.has(segment.index)) {
|
|
404
|
+
invalid = true;
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
changes.set(segment.index, replacement.text);
|
|
408
|
+
updates.set(candidate, changes);
|
|
409
|
+
}
|
|
410
|
+
if (invalid)
|
|
411
|
+
continue;
|
|
412
|
+
for (const [candidate, changes] of updates) {
|
|
413
|
+
const message = freezeMessage({
|
|
414
|
+
...candidate.event.data.message,
|
|
415
|
+
content: candidate.event.data.message.content.map((block, index) => changes.has(index) ? { type: 'text', text: changes.get(index) } : block),
|
|
416
|
+
});
|
|
417
|
+
const replaced = session.append('tool/result', { ...candidate.event.data, message }, {
|
|
418
|
+
surfaceOp: { op: 'replace', startSeq: candidate.seq, endSeq: candidate.seq }, sourceEventSeqs: [candidate.seq],
|
|
419
|
+
});
|
|
420
|
+
const key = String(session.id);
|
|
421
|
+
const work = pending.get(key) ?? { session, exposure, replacements: [], optimizations: new Map() };
|
|
422
|
+
work.optimizations.set(optimization, true);
|
|
423
|
+
work.replacements.push({ seq: replaced.seq, original: candidate.event, optimization, sentBlocks: [...changes].map(([index, text]) => ({ index, text })) });
|
|
424
|
+
pending.set(key, work);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
catch (error) {
|
|
429
|
+
restore(session);
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
return decision;
|
|
433
|
+
});
|
|
434
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import z from '@deepseek-ai/schemastery';
|
|
4
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
5
|
+
import { createSkillProvider } from './skills.js';
|
|
6
|
+
import { defaultModeFor, SessionModeTracker } from './mode.js';
|
|
7
|
+
import { registerCompression } from './compression.js';
|
|
8
|
+
import { registerBlocks } from './blocks.js';
|
|
9
|
+
import { statsReport } from './stats.js';
|
|
10
|
+
import { findCavemanBinary, guardedRuntimeFetch, runtimeSettings, verifiedRuntime } from './runtime.js';
|
|
11
|
+
import { registerMemoryRecovery } from './memory.js';
|
|
12
|
+
import { registerAttribution } from './attribution.js';
|
|
13
|
+
import { registerNative } from './native.js';
|
|
14
|
+
export const name = 'caveman';
|
|
15
|
+
export const inject = ['skills', 'tools', 'systemPrompt', 'llm'];
|
|
16
|
+
export const Config = z.object({
|
|
17
|
+
defaultMode: z.union([
|
|
18
|
+
z.const('caveman'), z.const('ultracave'), z.const('megacave'), z.const('off'), z.const('manual'),
|
|
19
|
+
]),
|
|
20
|
+
inputCompression: z.boolean(),
|
|
21
|
+
middlewareEndpoint: z.string().default('http://127.0.0.1:8787'),
|
|
22
|
+
blocksBinary: z.string().min(1),
|
|
23
|
+
browseBinary: z.string().min(1),
|
|
24
|
+
mcpBinary: z.string().min(1),
|
|
25
|
+
memoryBinary: z.string().min(1),
|
|
26
|
+
});
|
|
27
|
+
/** Register skills and reinforce the selected mode per session. */
|
|
28
|
+
export function apply(ctx, config = {}) {
|
|
29
|
+
const root = fileURLToPath(new URL('../vendor/caveman/skills/', import.meta.url));
|
|
30
|
+
const modes = new SessionModeTracker();
|
|
31
|
+
const settings = runtimeSettings();
|
|
32
|
+
registerAttribution(ctx, config.middlewareEndpoint ?? 'http://127.0.0.1:8787');
|
|
33
|
+
registerNative(ctx, config.middlewareEndpoint ?? 'http://127.0.0.1:8787', { mode: settings.nativeMode, profile: settings.nativeProfile, core: settings.core });
|
|
34
|
+
if (settings.core) {
|
|
35
|
+
let core = readFileSync(new URL('../vendor/caveman/skills/native/native-core.md', import.meta.url), 'utf8').trim();
|
|
36
|
+
if (settings.coreLeanBuild) {
|
|
37
|
+
const lean = readFileSync(new URL('../vendor/caveman/skills/lean-build/SKILL.md', import.meta.url), 'utf8')
|
|
38
|
+
.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/u, '').trim();
|
|
39
|
+
core += ` ${lean}`;
|
|
40
|
+
}
|
|
41
|
+
ctx.systemPrompt.section({
|
|
42
|
+
name: 'caveman:core', order: ctx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') + 10, interpolate: false,
|
|
43
|
+
text: context => {
|
|
44
|
+
const preset = context.agent && ctx.get('agentPresets')?.composedPreset(context.agent.ctx);
|
|
45
|
+
return preset === 'cavecrew-investigator' || preset === 'cavecrew-builder' || preset === 'cavecrew-reviewer' ? '' : core;
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
ctx.skills.registerProvider(control => createSkillProvider(root, control));
|
|
50
|
+
if (config.inputCompression !== false && settings.input) {
|
|
51
|
+
const endpoint = config.middlewareEndpoint ?? 'http://127.0.0.1:8787';
|
|
52
|
+
const automatic = config.inputCompression === true ? undefined : {
|
|
53
|
+
fetch: guardedRuntimeFetch(endpoint), available: (signal) => verifiedRuntime(endpoint, process.env, signal),
|
|
54
|
+
};
|
|
55
|
+
registerCompression(ctx, endpoint, automatic);
|
|
56
|
+
}
|
|
57
|
+
const blocks = settings.scripts ? findCavemanBinary('blocks', config.blocksBinary) : undefined;
|
|
58
|
+
if (blocks)
|
|
59
|
+
registerBlocks(ctx, blocks);
|
|
60
|
+
const browse = settings.browse ? findCavemanBinary('browse', config.browseBinary) : undefined;
|
|
61
|
+
const mcp = settings.mcp ? findCavemanBinary('mcp', config.mcpBinary) : undefined;
|
|
62
|
+
const memory = settings.mcp && settings.memory ? findCavemanBinary('memory', config.memoryBinary) : undefined;
|
|
63
|
+
if (memory)
|
|
64
|
+
ctx.inject(['subprocess', 'workingDirectory'], scoped => registerMemoryRecovery(scoped, memory));
|
|
65
|
+
const servers = [{ name: 'caveman', binary: mcp, args: [] }, { name: 'caveman_browse', binary: browse, args: [] }, { name: 'cavemem', binary: memory, args: ['mcp'] }]
|
|
66
|
+
.filter((server) => server.binary !== undefined);
|
|
67
|
+
if (servers.length) {
|
|
68
|
+
ctx.inject(['mcpManager'], scoped => {
|
|
69
|
+
for (const server of servers) {
|
|
70
|
+
if (!scoped.mcpManager.list().some(entry => entry.name === server.name && entry.configured)) {
|
|
71
|
+
scoped.mcpManager.register(server.name, { transport: 'stdio', command: server.binary, args: server.args });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
|
|
77
|
+
const decision = await next();
|
|
78
|
+
if (decision.kind === 'reject')
|
|
79
|
+
return decision;
|
|
80
|
+
const preset = ctx.get('agentPresets')?.composedPreset(agent.ctx);
|
|
81
|
+
if (preset === 'cavecrew-investigator' || preset === 'cavecrew-builder' || preset === 'cavecrew-reviewer')
|
|
82
|
+
return decision;
|
|
83
|
+
const directMessages = decision.messages.filter(message => message.source.kind === 'user');
|
|
84
|
+
if (directMessages.length === 0)
|
|
85
|
+
return decision;
|
|
86
|
+
signal.throwIfAborted();
|
|
87
|
+
const statsRequest = directMessages.map(message => message.content
|
|
88
|
+
.filter(block => block.type === 'text').map(block => block.text).join('\n'))
|
|
89
|
+
.map(text => /^\/caveman(?::caveman)?-stats(?:\s+(.*))?$/u.exec(text.trim()))
|
|
90
|
+
.reverse().find(match => match !== null);
|
|
91
|
+
if (statsRequest) {
|
|
92
|
+
const report = await statsReport(ctx, agent.session, statsRequest[1]?.trim() ?? '', signal);
|
|
93
|
+
const reminder = createUserMessage({
|
|
94
|
+
source: { kind: 'dsh-caveman-stats', form: 'notice' },
|
|
95
|
+
content: [{ type: 'text', text: `Print this report verbatim in a fenced code block. Do not infer savings.\n\n${report}` }],
|
|
96
|
+
});
|
|
97
|
+
return { ...decision, messages: [...decision.messages, reminder] };
|
|
98
|
+
}
|
|
99
|
+
const directory = ctx.get('workingDirectory');
|
|
100
|
+
const cwd = directory ? await directory.ensure(agent, signal) : agent.session.header.cwd;
|
|
101
|
+
const selected = modes.resolve(defaultModeFor(config.defaultMode, cwd), agent.session, directMessages);
|
|
102
|
+
if (selected.action === 'one-shot' || (selected.mode === 'off' && selected.action === 'none'))
|
|
103
|
+
return decision;
|
|
104
|
+
let text;
|
|
105
|
+
if (selected.action === 'status') {
|
|
106
|
+
text = `Report this status without changing it: Caveman mode: ${selected.mode}`;
|
|
107
|
+
}
|
|
108
|
+
else if (selected.action === 'unresolved') {
|
|
109
|
+
text = 'The requested Caveman mode is not recognized. Keep the current mode unchanged and explain the valid commands.';
|
|
110
|
+
}
|
|
111
|
+
else if (selected.mode === 'off') {
|
|
112
|
+
text = 'Caveman mode is off. Stop following previous Caveman mode instructions and resume the normal response style.';
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
const skill = await ctx.skills.get(selected.mode, { scope: agent, signal });
|
|
116
|
+
signal.throwIfAborted();
|
|
117
|
+
if (!skill)
|
|
118
|
+
throw new Error(`dsh-caveman: ${selected.mode} skill is unavailable`);
|
|
119
|
+
text = `Caveman mode: ${selected.mode}\n\n${skill.content}`;
|
|
120
|
+
}
|
|
121
|
+
const reminder = createUserMessage({
|
|
122
|
+
source: { kind: 'dsh-caveman-mode', form: 'instructions', mode: selected.mode },
|
|
123
|
+
content: [{ type: 'text', text }],
|
|
124
|
+
});
|
|
125
|
+
return { ...decision, messages: [...decision.messages, reminder] };
|
|
126
|
+
});
|
|
127
|
+
}
|
package/lib/memory.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Expose the exact-original operation that the memory server's MCP tools omit. */
|
|
2
|
+
export function registerMemoryRecovery(ctx, binary) {
|
|
3
|
+
if (ctx.tools.get('cavemem_recover'))
|
|
4
|
+
return;
|
|
5
|
+
const tool = {
|
|
6
|
+
name: 'cavemem_recover',
|
|
7
|
+
description: 'Read the exact original for a recovery_handle returned by cavemem_recall. The handle has the form ccr_ followed by 32 lowercase hexadecimal characters.',
|
|
8
|
+
parameters: {
|
|
9
|
+
type: 'object', additionalProperties: false, required: ['handle'],
|
|
10
|
+
properties: { handle: { type: 'string' } },
|
|
11
|
+
},
|
|
12
|
+
timeoutMs: 15_000,
|
|
13
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
14
|
+
async execute(value, exec) {
|
|
15
|
+
const handle = typeof value === 'object' && value !== null && 'handle' in value ? value.handle : undefined;
|
|
16
|
+
if (typeof handle !== 'string' || !/^ccr_[a-f0-9]{32}$/u.test(handle))
|
|
17
|
+
throw new Error('Invalid memory recovery handle');
|
|
18
|
+
const cwd = exec.agent ? await ctx.workingDirectory.ensure(exec.agent, exec.signal) : process.cwd();
|
|
19
|
+
const executable = await ctx.subprocess.resolveExecutable(binary, {}, exec.signal);
|
|
20
|
+
const child = ctx.subprocess.spawn({
|
|
21
|
+
argv: [executable, 'recover', handle], cwd, signal: exec.signal, graceMs: 1000,
|
|
22
|
+
stdio: { stdin: 'ignore', stdout: { maxBytes: 262_144 }, stderr: { maxBytes: 4096 } },
|
|
23
|
+
});
|
|
24
|
+
const outcome = await child.done;
|
|
25
|
+
exec.signal.throwIfAborted();
|
|
26
|
+
const stdout = child.collected.stdout?.readFrom(0);
|
|
27
|
+
const stderr = child.collected.stderr?.readFrom(0);
|
|
28
|
+
if (!stdout || !stderr || outcome.signal || outcome.exitCode !== 0 || stdout.lossy) {
|
|
29
|
+
throw new Error(`Memory recovery failed: ${stderr?.text.slice(0, 1024) || 'original unavailable'}`);
|
|
30
|
+
}
|
|
31
|
+
return stdout.text;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
ctx.tools.register(tool);
|
|
35
|
+
}
|
package/lib/mode.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
const require = createRequire(import.meta.url);
|
|
3
|
+
const parser = require('../vendor/caveman/src/hooks/caveman-parse.js');
|
|
4
|
+
const modeConfig = require('../vendor/caveman/src/hooks/caveman-config.js');
|
|
5
|
+
/** A profile override wins; otherwise follow environment and file resolution. */
|
|
6
|
+
export function defaultModeFor(configured, cwd) {
|
|
7
|
+
if (configured !== undefined)
|
|
8
|
+
return configured;
|
|
9
|
+
const mode = modeConfig.getDefaultMode(cwd);
|
|
10
|
+
return mode === 'manual' || mode === 'off' || mode === 'caveman' || mode === 'ultracave' || mode === 'megacave' ? mode : 'caveman';
|
|
11
|
+
}
|
|
12
|
+
function transition(mode, message, configured) {
|
|
13
|
+
if (message.source.kind !== 'user')
|
|
14
|
+
return { mode, action: 'none' };
|
|
15
|
+
const text = message.content.filter(block => block.type === 'text').map(block => block.text ?? '').join('\n');
|
|
16
|
+
const change = parser.parseModeChange(text, { getDefaultMode: () => configured });
|
|
17
|
+
if (!change)
|
|
18
|
+
return { mode, action: 'none' };
|
|
19
|
+
if (change.action === 'status')
|
|
20
|
+
return { mode, action: 'status' };
|
|
21
|
+
if (change.action === 'unresolved')
|
|
22
|
+
return { mode, action: 'unresolved' };
|
|
23
|
+
if (change.action === 'clear')
|
|
24
|
+
return { mode: 'off', action: 'change' };
|
|
25
|
+
if (change.mode && parser.INDEPENDENT_MODES.has(change.mode))
|
|
26
|
+
return { mode, action: 'one-shot' };
|
|
27
|
+
if (change.mode === 'caveman' || change.mode === 'ultracave' || change.mode === 'megacave') {
|
|
28
|
+
return { mode: change.mode, action: 'change' };
|
|
29
|
+
}
|
|
30
|
+
return { mode, action: 'none' };
|
|
31
|
+
}
|
|
32
|
+
function replay(mode, configured, events) {
|
|
33
|
+
for (const event of events) {
|
|
34
|
+
if (event.type !== 'user/message' || !event.data || typeof event.data !== 'object')
|
|
35
|
+
continue;
|
|
36
|
+
const message = event.data;
|
|
37
|
+
if (!message.source || !Array.isArray(message.content))
|
|
38
|
+
continue;
|
|
39
|
+
mode = transition(mode, message, configured).mode;
|
|
40
|
+
}
|
|
41
|
+
return mode;
|
|
42
|
+
}
|
|
43
|
+
function resolvePending(mode, configured, pending) {
|
|
44
|
+
let action = 'none';
|
|
45
|
+
for (const message of pending) {
|
|
46
|
+
const result = transition(mode, message, configured);
|
|
47
|
+
mode = result.mode;
|
|
48
|
+
if (result.action !== 'none')
|
|
49
|
+
action = result.action;
|
|
50
|
+
}
|
|
51
|
+
return { mode, action };
|
|
52
|
+
}
|
|
53
|
+
/** Replay only user-authored messages, then evaluate the incoming batch. */
|
|
54
|
+
export function resolveMode(configured, events, pending) {
|
|
55
|
+
const initial = configured === 'manual' ? 'off' : configured;
|
|
56
|
+
return resolvePending(replay(initial, configured, events), configured, pending);
|
|
57
|
+
}
|
|
58
|
+
/** Incrementally replay immutable session logs; pending messages are never cached. */
|
|
59
|
+
export class SessionModeTracker {
|
|
60
|
+
states = new WeakMap();
|
|
61
|
+
resolve(configured, session, pending) {
|
|
62
|
+
const end = session.seq;
|
|
63
|
+
const previous = this.states.get(session);
|
|
64
|
+
const reusable = previous && previous.configured === configured && previous.seq <= end;
|
|
65
|
+
const initial = reusable ? previous.mode : configured === 'manual' ? 'off' : configured;
|
|
66
|
+
const events = session.snapshotEvents(reusable ? previous.seq : undefined, end);
|
|
67
|
+
const mode = replay(initial, configured, events);
|
|
68
|
+
this.states.set(session, { seq: end, configured, mode });
|
|
69
|
+
return resolvePending(mode, configured, pending);
|
|
70
|
+
}
|
|
71
|
+
}
|