@crocketc/dsh-capability-manager 0.0.0-stage → 0.1.1

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/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@crocketc/dsh-capability-manager",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Manage Agent capabilities and first-request token budgets in DeepSeek Harness",
5
+ "repository": "git+https://github.com/crocketc/dsh-capability-manager.git",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/index.js",
9
+ "./client": "./src/client.js"
10
+ },
11
+ "files": ["src", "data", "cordis.patch.yml"],
12
+ "engines": { "node": ">=24.9" },
13
+ "scripts": { "test": "node --test" },
14
+ "dsh": {
15
+ "bundle": { "patch": "./cordis.patch.yml" },
16
+ "client": { "platform": "web" }
17
+ }
18
+ }
@@ -0,0 +1,337 @@
1
+ import { estimateTextTokens, measureInitialRequest } from './measurement.js';
2
+
3
+ const EMPTY_GROUPS = ['mcp', 'dsh', 'plugin', 'unknown'];
4
+ const AUTOMATIC_SOURCES = new Set(['runtime-context', 'time-context', 'tmux-context']);
5
+
6
+ function asSet(value) {
7
+ return value instanceof Set ? value : new Set(value ?? []);
8
+ }
9
+
10
+ function mapGet(map, key) {
11
+ if (map instanceof Map) return map.get(key);
12
+ if (map && typeof map === 'object') return map[key];
13
+ return undefined;
14
+ }
15
+
16
+ function groupFor(name, groupByName) {
17
+ const value = mapGet(groupByName, name);
18
+ if (value === 'builtin' || value === 'dsh') return 'dsh';
19
+ if (value === 'mcp' || value === 'plugin' || value === 'unknown') return value;
20
+ return 'unknown';
21
+ }
22
+
23
+ function topLevelFields(body, offset, groupByName) {
24
+ const fields = [];
25
+ const pattern = /^ (?:"((?:[^"\\]|\\.)*)"|([A-Za-z_$][\w$]*)):\s/gm;
26
+ for (const match of body.matchAll(pattern)) {
27
+ let name;
28
+ try { name = match[1] === undefined ? match[2] : JSON.parse(`"${match[1]}"`); }
29
+ catch { continue; }
30
+ const propertyStart = match.index;
31
+ const lineStart = body.lastIndexOf('\n', propertyStart - 1) + 1;
32
+ let start = lineStart;
33
+ const previousLineEnd = Math.max(0, lineStart - 1);
34
+ const previousLineStart = body.lastIndexOf('\n', previousLineEnd - 1) + 1;
35
+ const previousLine = body.slice(previousLineStart, previousLineEnd).trim();
36
+ if (previousLine.startsWith('/**') && previousLine.endsWith('*/')) start = previousLineStart;
37
+ fields.push({ name, start: offset + start });
38
+ }
39
+ return fields;
40
+ }
41
+
42
+ /** Extract actual per-tool property fragments from DSH's two rendered SDK maps. */
43
+ export function sdkDeclarations(text, groupByName = new Map()) {
44
+ if (typeof text !== 'string') throw new TypeError('SDK text must be a string');
45
+ const markers = [
46
+ ['interface ToolArgsMap {', '\n\ninterface ToolOutputMap {'],
47
+ ['interface ToolOutputMap {', '\n\ntype ToolName ='],
48
+ ];
49
+ const spans = [];
50
+ for (const [open, close] of markers) {
51
+ const openAt = text.indexOf(open);
52
+ if (openAt < 0) continue;
53
+ const bodyStart = openAt + open.length;
54
+ const closeAt = text.indexOf(close, bodyStart);
55
+ if (closeAt < 0) continue;
56
+ const body = text.slice(bodyStart, closeAt);
57
+ const innerEnd = body.lastIndexOf('\n}');
58
+ spans.push({ start: bodyStart, end: bodyStart + (innerEnd < 0 ? body.length : innerEnd), body });
59
+ }
60
+ const entries = [];
61
+ for (const span of spans) {
62
+ const fields = topLevelFields(span.body, span.start, groupByName);
63
+ for (let index = 0; index < fields.length; index += 1) {
64
+ const field = fields[index];
65
+ const end = fields[index + 1]?.start ?? span.end;
66
+ entries.push({
67
+ name: field.name,
68
+ source: groupFor(field.name, groupByName),
69
+ text: text.slice(field.start, end),
70
+ start: field.start,
71
+ });
72
+ }
73
+ }
74
+ entries.sort((a, b) => a.start - b.start);
75
+ return entries.map(({ name, source, text: fragment }) => ({ name, source, text: fragment }));
76
+ }
77
+
78
+ function seqOf(event, index) {
79
+ return Number.isSafeInteger(event?.seq) ? event.seq : index;
80
+ }
81
+
82
+ function applySurfaceEvent(surface, event) {
83
+ if (event.surfaceOp === 'append') {
84
+ surface.push(event);
85
+ return;
86
+ }
87
+ const op = event.surfaceOp;
88
+ if (op?.op !== 'replace') return;
89
+ const first = surface.findIndex(item => item.seq === op.startSeq);
90
+ const last = surface.findIndex(item => item.seq === op.endSeq);
91
+ if (first < 0 || last < first) {
92
+ // A replacement may target a source omitted from a partial event stream.
93
+ // Keep the latest event visible rather than silently losing its prompt.
94
+ surface.push(event);
95
+ return;
96
+ }
97
+ surface.splice(first, last - first + 1, event);
98
+ }
99
+
100
+ function textOfBlock(block) {
101
+ return block?.type === 'text' && typeof block.text === 'string' ? block.text : '';
102
+ }
103
+
104
+ function workspaceMarked(source, context) {
105
+ if (source?.workspace === true || source?.scope === 'workspace' || source?.origin === 'workspace') return true;
106
+ return context.workspaceId !== undefined && source?.workspaceId === context.workspaceId;
107
+ }
108
+
109
+ function sourceWorkspaceTokenCount(message, context) {
110
+ const names = asSet(context.workspaceSkillNames);
111
+ if (names.size === 0) return undefined;
112
+ const content = (message.content ?? []).map(textOfBlock).join('\n');
113
+ const catalogEntries = message.source?.entries;
114
+ if (!Array.isArray(catalogEntries)) return undefined;
115
+ const workspaceLines = [];
116
+ for (const entry of catalogEntries) {
117
+ if (typeof entry?.name !== 'string' || !names.has(entry.name)) continue;
118
+ const line = content.split('\n').find(candidate => candidate.includes(`\`${entry.name}\`:`));
119
+ if (line !== undefined) workspaceLines.push(line);
120
+ }
121
+ return workspaceLines.length === 0 ? 0 : estimateTextTokens(workspaceLines.join('\n'));
122
+ }
123
+
124
+ function promptKind(name, context) {
125
+ const explicit = mapGet(context.promptKindByName, name);
126
+ if (['base-system', 'automatic', 'skill-catalog', 'tool-prompt', 'ptc-sdk', 'other'].includes(explicit)) return explicit;
127
+ if (asSet(context.baseSectionNames).has(name)) return 'base-system';
128
+ if (asSet(context.skillCatalogSectionNames).has(name)) return 'skill-catalog';
129
+ if (name === (context.ptcSectionName ?? 'tools:sdk')) return 'ptc-sdk';
130
+ if (name.startsWith('tools:') || name.startsWith('tool:')) return 'tool-prompt';
131
+ return 'automatic';
132
+ }
133
+
134
+ function addSystemMessage(message, promptParts, ptcSections, context) {
135
+ const content = Array.isArray(message.content) ? message.content : [];
136
+ const sections = message.source?.sections;
137
+ if (!Array.isArray(sections) || sections.length === 0) {
138
+ const text = content.map(textOfBlock).filter(Boolean).join('\n\n');
139
+ if (text && context.firstSystemSections?.map(section => section.text).join('\n\n') === text) {
140
+ for (const section of context.firstSystemSections) {
141
+ const kind = promptKind(section.name, context);
142
+ if (kind === 'ptc-sdk') ptcSections.push(section.text);
143
+ else promptParts.push({ kind, text: section.text });
144
+ }
145
+ return;
146
+ }
147
+ if (text) promptParts.push({ kind: 'other', text });
148
+ return;
149
+ }
150
+
151
+ const attributed = new Set();
152
+ const addIndex = (index, kind) => {
153
+ if (!Number.isInteger(index) || index < 0 || index >= content.length || attributed.has(index)) return;
154
+ attributed.add(index);
155
+ const text = textOfBlock(content[index]);
156
+ if (!text) return;
157
+ if (kind === 'ptc-sdk') ptcSections.push(text);
158
+ else promptParts.push({ kind, text });
159
+ };
160
+
161
+ for (const section of sections) {
162
+ const kind = promptKind(section.name, context);
163
+ if (section.state === 'active') addIndex(section.contentIndex, kind);
164
+ for (const index of section.noticeIndex ?? []) addIndex(index, kind);
165
+ }
166
+ for (let index = 0; index < content.length; index += 1) addIndex(index, 'other');
167
+ }
168
+
169
+ function addRuntimeMessage(message, promptParts, workspaceSkillTokens, context) {
170
+ const source = message.source ?? {};
171
+ const text = (message.content ?? []).map(textOfBlock).filter(Boolean).join('\n\n');
172
+ if (!text) return workspaceSkillTokens;
173
+ if (source.kind === 'skill-catalog') {
174
+ const workspace = workspaceMarked(source, context);
175
+ promptParts.push({ kind: 'skill-catalog', text, ...(workspace ? { workspace: true } : {}) });
176
+ if (!workspace) {
177
+ const perSkillTokens = sourceWorkspaceTokenCount(message, context);
178
+ if (perSkillTokens !== undefined) workspaceSkillTokens += perSkillTokens;
179
+ }
180
+ return workspaceSkillTokens;
181
+ }
182
+ if (AUTOMATIC_SOURCES.has(source.kind)) {
183
+ const sections = source.sections;
184
+ const included = sections?.filter(section => !excludedRuntimeSection(section.name));
185
+ if (!included || included.length === sections.length) promptParts.push({ kind: 'automatic', text });
186
+ else if (included.length) {
187
+ const persistedBody = sections.map(section => section.text).join('\n\n');
188
+ const body = included.map(section => section.text).join('\n\n');
189
+ promptParts.push({ kind: 'automatic', text: text.includes(persistedBody) ? text.replace(persistedBody, body) : body });
190
+ }
191
+ return workspaceSkillTokens;
192
+ }
193
+ // User text, workspace instructions, chat history, and arbitrary plugin
194
+ // messages are deliberately outside the P0 initial-injection budget.
195
+ return workspaceSkillTokens;
196
+ }
197
+
198
+ export function excludedRuntimeSection(name = '') {
199
+ return /working.directory|project.instruction|workspace.instruction|agent.instruction/i.test(name);
200
+ }
201
+
202
+ /**
203
+ * Read a settled first request from DSH's durable SessionEvent shape.
204
+ *
205
+ * `recordEvents` is `session.snapshotEvents()` (or an equivalent ordered array
206
+ * of `{type, seq, data, surfaceOp, sourceEventSeqs}` records). `context` may
207
+ * supply `presetId`, `workspaceId`, `groupByName`, `baseSectionNames`,
208
+ * `promptKindByName`, `skillCatalogSectionNames`, `workspaceSkillNames`,
209
+ * `ptcSectionName`, and exact `ptcDeclarations` extracted by the live PTC
210
+ * assembler. Returns `undefined` until both the initial header and its matching
211
+ * assistant/message have been committed.
212
+ */
213
+ export function readInitial(recordEvents, context = {}) {
214
+ if (!Array.isArray(recordEvents)) throw new TypeError('recordEvents must be an array of SessionEvent records');
215
+ const events = recordEvents.map((event, index) => ({ event, index, seq: seqOf(event, index) }))
216
+ .sort((a, b) => a.seq - b.seq);
217
+ const headerEntry = events.find(({ event }) => event?.type === 'request/header' && event.data?.reason === 'initial');
218
+ if (!headerEntry) return undefined;
219
+
220
+ const stepEntry = [...events].reverse().find(({ event, seq }) => seq < headerEntry.seq && event?.type === 'step/start');
221
+ if (!stepEntry) return undefined;
222
+ const { turn, step } = stepEntry.event.data ?? {};
223
+ if (!Number.isInteger(turn) || !Number.isInteger(step)) return undefined;
224
+ const assistantEntry = events.find(({ event, seq }) => seq > headerEntry.seq
225
+ && event?.type === 'assistant/message'
226
+ && event.data?.turn === turn && event.data?.step === step);
227
+ if (!assistantEntry) return undefined;
228
+
229
+ const surface = [];
230
+ for (const { event, seq } of events) {
231
+ if (seq >= headerEntry.seq) break;
232
+ if (['system/message', 'user/message', 'assistant/message', 'tool/result'].includes(event?.type)) {
233
+ applySurfaceEvent(surface, event);
234
+ }
235
+ }
236
+
237
+ const promptParts = [];
238
+ const ptcSections = [];
239
+ let workspaceSkillCatalogTokens = 0;
240
+ for (const event of surface) {
241
+ if (event.type === 'system/message') {
242
+ addSystemMessage(event.data?.message ?? {}, promptParts, ptcSections, context);
243
+ } else if (event.type === 'user/message') {
244
+ workspaceSkillCatalogTokens = addRuntimeMessage(event.data ?? {}, promptParts, workspaceSkillCatalogTokens, context);
245
+ }
246
+ }
247
+
248
+ const header = headerEntry.event.data.header ?? {};
249
+ const schemas = Array.isArray(header.tools) ? header.tools : [];
250
+ const tools = schemas.map(schema => {
251
+ const name = schema.name;
252
+ const mode = name === 'run_code' ? 'run-code' : (mapGet(context.toolModeByName, name) ?? 'native');
253
+ return { name, source: groupFor(name, context.groupByName), mode, schema };
254
+ });
255
+ const ptcDeclarations = context.ptcDeclarations
256
+ ?? sdkDeclarations(ptcSections.join('\n\n'), context.groupByName);
257
+ const ptcNames = new Map();
258
+ for (const declaration of ptcDeclarations) ptcNames.set(declaration.name, declaration.source);
259
+ for (const [name, source] of ptcNames) tools.push({ name, source, mode: 'ptc' });
260
+
261
+ const usage = assistantEntry.event.data?.usage;
262
+ const providerUsage = Number.isSafeInteger(usage?.inputTokens) && usage.inputTokens >= 0
263
+ ? { inputTokens: usage.inputTokens }
264
+ : undefined;
265
+ const route = header.config ?? {};
266
+ const requestPtcText = ptcSections.join('\n\n');
267
+ const skillCount = surface.reduce((count, event) => count +
268
+ (event.type === 'user/message' && event.data?.source?.kind === 'skill-catalog'
269
+ ? event.data.source.entries?.length ?? 0 : 0), 0);
270
+ const measured = measureInitialRequest({
271
+ request: { header: { reason: 'initial', startsSeries: true }, turn, step },
272
+ promptParts,
273
+ tools,
274
+ ...(ptcSections.length === 0 ? {} : {
275
+ ptcSdk: {
276
+ text: requestPtcText,
277
+ declarations: ptcDeclarations,
278
+ },
279
+ }),
280
+ ...(providerUsage === undefined ? {} : { providerUsage }),
281
+ });
282
+ measured.prompt.workspaceSkillCatalogTokens += workspaceSkillCatalogTokens;
283
+
284
+ return {
285
+ ...(context.presetId === undefined ? {} : { presetId: context.presetId }),
286
+ ...(context.workspaceId === undefined ? {} : { workspaceId: context.workspaceId }),
287
+ request: {
288
+ seq: headerEntry.seq,
289
+ turn,
290
+ step,
291
+ ...(typeof route.provider === 'string' ? { provider: route.provider } : {}),
292
+ ...(typeof route.model === 'string' ? { model: route.model } : {}),
293
+ },
294
+ measured,
295
+ count: measured.toolRows.length + skillCount,
296
+ ...(workspaceSkillCatalogTokens > 0 ? { workspaceSkillCatalogTokens } : {}),
297
+ };
298
+ }
299
+
300
+ /** Format the additive budget rows for the UI, omitting zero rows. */
301
+ export function formatBudget(measuredInput, count) {
302
+ const measured = measuredInput?.measured ?? measuredInput;
303
+ if (!measured?.prompt || !measured?.nativeTools || !measured?.totals) {
304
+ throw new TypeError('measured must be a measurement result or readInitial result');
305
+ }
306
+ const prompt = measured.prompt;
307
+ const native = measured.nativeTools;
308
+ const ptcAttribution = measured.ptcToolAttribution ?? { mcpTokens: 0, dshTokens: 0, pluginTokens: 0, unknownTokens: 0 };
309
+ const automaticTokens = prompt.automaticTokens + prompt.otherTokens;
310
+ const capability = measured.totals.agentCapabilityTokens;
311
+ const total = measured.totals.estimatedTotalTokens;
312
+ const workspaceSkills = Math.min(prompt.skillCatalogTokens, prompt.workspaceSkillCatalogTokens ?? 0);
313
+ const sharedSkills = prompt.skillCatalogTokens - workspaceSkills;
314
+ const rows = [
315
+ ['base-system', '基础系统提示词', prompt.baseSystemTokens],
316
+ ['automatic', '其他自动注入', automaticTokens],
317
+ ['skill-catalog', '全局技能目录', sharedSkills],
318
+ ['workspace-skill-catalog', '工作区技能目录', workspaceSkills],
319
+ ['tool-prompt', '工具提示', prompt.toolPromptTokens],
320
+ ['mcp-tools', 'MCP工具定义', native.mcpTokens],
321
+ ['builtin-tools', '内置工具定义', native.dshTokens],
322
+ ['plugin-tools', '其他插件工具定义', native.pluginTokens],
323
+ ['unknown-tools', '未归因工具定义', native.unknownTokens],
324
+ ['ptc-shared', 'PTC共享声明与模板', measured.ptc?.sharedTokens ?? 0],
325
+ ['ptc-mcp-tools', 'PTC MCP工具声明', ptcAttribution.mcpTokens],
326
+ ['ptc-builtin-tools', 'PTC 内置工具声明', ptcAttribution.dshTokens],
327
+ ['ptc-plugin-tools', 'PTC其他插件工具声明', ptcAttribution.pluginTokens],
328
+ ['ptc-unknown-tools', 'PTC未归因工具声明', ptcAttribution.unknownTokens],
329
+ ['run-code', 'run_code入口', native.runCodeTokens],
330
+ ];
331
+ return {
332
+ count,
333
+ capability,
334
+ total,
335
+ breakdown: rows.filter(([, , tokens]) => tokens > 0).map(([key, label, tokens]) => ({ key, label, tokens })),
336
+ };
337
+ }