@lmzhen/dsh-evolution-core 0.37.1 → 0.39.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/README.md +4 -2
- package/lib/composition/index.js +2 -2
- package/lib/{composition-DckDtQTR.js → composition-dy0gJWDd.js} +1 -1
- package/lib/{ensure-CLF9YeBD.js → ensure-B4fjEI0w.js} +3 -10
- package/lib/index.js +67 -1302
- package/lib/platform/index.js +4 -0
- package/lib/platform-Be-_wSVz.js +113 -0
- package/lib/presets-C8vuCuNA.js +27 -0
- package/lib/restrictor.js +7 -7
- package/lib/runtime/plugin.js +197 -0
- package/lib/session-projection-CXUNPkq9.js +1250 -0
- package/lib/subagent/index.js +1 -1
- package/lib/tools-DzcNFex2.js +20 -0
- package/lib/types/composition/ensure.js +3 -13
- package/lib/types/events.d.ts +1 -1
- package/lib/types/index.d.ts +1 -0
- package/lib/types/index.js +1 -0
- package/lib/types/opt-in.d.ts +1 -1
- package/lib/types/opt-in.js +1 -1
- package/lib/types/params.js +2 -2
- package/lib/types/platform/index.d.ts +21 -0
- package/lib/types/platform/index.js +12 -0
- package/lib/types/platform/llm.d.ts +46 -0
- package/lib/types/platform/llm.js +75 -0
- package/lib/types/platform/presets.d.ts +31 -0
- package/lib/types/platform/presets.js +31 -0
- package/lib/types/platform/projections.d.ts +30 -0
- package/lib/types/platform/projections.js +31 -0
- package/lib/types/platform/tools.d.ts +23 -0
- package/lib/types/platform/tools.js +21 -0
- package/lib/types/platform-line.generated.d.ts +6 -6
- package/lib/types/platform-line.generated.js +6 -6
- package/lib/types/platform-services.d.ts +1 -1
- package/lib/types/platform-services.js +4 -1
- package/lib/types/restrictor.js +7 -9
- package/lib/types/review-context.d.ts +20 -0
- package/lib/types/review-context.js +28 -0
- package/lib/types/runtime/llm.d.ts +34 -0
- package/lib/types/runtime/llm.js +71 -0
- package/lib/types/runtime/platform.d.ts +35 -0
- package/lib/types/runtime/platform.js +38 -0
- package/lib/types/runtime/plugin.d.ts +10 -0
- package/lib/types/runtime/plugin.js +11 -0
- package/lib/types/runtime/projections.d.ts +29 -0
- package/lib/types/runtime/projections.js +62 -0
- package/lib/types/scope.d.ts +1 -1
- package/lib/types/session-projection.d.ts +26 -53
- package/lib/types/session-projection.js +22 -58
- package/lib/types/skill-reads.js +3 -3
- package/lib/types/skill-store.js +3 -0
- package/lib/types/subagent/types.d.ts +1 -1
- package/lib/types/tool-dispatch.d.ts +2 -2
- package/lib/types/tool-dispatch.js +3 -3
- package/package.json +30 -16
|
@@ -0,0 +1,1250 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region lib/types/citations.js
|
|
3
|
+
/**
|
|
4
|
+
* Citation resolution for skill bodies and support files (design §5.2).
|
|
5
|
+
*
|
|
6
|
+
* WHY this exists beside `supportRefs` (skill-store.ts): that scanner answers
|
|
7
|
+
* "does this text contain a path-shaped token", which is the right question
|
|
8
|
+
* when a package is being ARCHIVED — every such path may dangle — and the wrong
|
|
9
|
+
* one when a section is only being MOVED, where nothing leaves and the only
|
|
10
|
+
* thing that changes is the directory a citation is read from. Measured false
|
|
11
|
+
* positives of the token scan: a URL tail (`https://host/references/x.md`), a
|
|
12
|
+
* category path the original Hermes documents as legitimate
|
|
13
|
+
* (`skills/scripts/foo.py`), and a prose command line
|
|
14
|
+
* (`npm run scripts/build.mjs`).
|
|
15
|
+
*
|
|
16
|
+
* CONTRACT: a token whose path STARTS WITH a support directory is a citation of
|
|
17
|
+
* this skill and is resolved from the SKILL ROOT, in whichever file it is
|
|
18
|
+
* written. A token that merely contains a support directory further along its
|
|
19
|
+
* path belongs to something else: it is reported as `foreign` and never
|
|
20
|
+
* resolved.
|
|
21
|
+
*
|
|
22
|
+
* PURE: existence is decided against the caller's file list, so identical
|
|
23
|
+
* inputs always answer the same report.
|
|
24
|
+
*/
|
|
25
|
+
/** Support directories that make a path a citation of the owning skill. */
|
|
26
|
+
const CITATION_SUPPORT_DIRS = [
|
|
27
|
+
"references",
|
|
28
|
+
"templates",
|
|
29
|
+
"scripts",
|
|
30
|
+
"assets"
|
|
31
|
+
];
|
|
32
|
+
/** Scan budget: bounded so a pathological body cannot stall a maintenance run. */
|
|
33
|
+
const DEFAULT_CITATION_REF_BUDGET = 500;
|
|
34
|
+
/** Words that introduce an executable command rather than a citation. */
|
|
35
|
+
const PROSE_COMMAND_PREFIXES = [
|
|
36
|
+
"npm",
|
|
37
|
+
"pnpm",
|
|
38
|
+
"yarn",
|
|
39
|
+
"npx",
|
|
40
|
+
"node",
|
|
41
|
+
"python",
|
|
42
|
+
"python3",
|
|
43
|
+
"bash",
|
|
44
|
+
"sh",
|
|
45
|
+
"git",
|
|
46
|
+
"gh",
|
|
47
|
+
"run"
|
|
48
|
+
];
|
|
49
|
+
const TOKEN_RE = /(?:references|templates|scripts|assets)\/[A-Za-z0-9._/-]+/g;
|
|
50
|
+
const TOKEN_CHAR_RE = /[A-Za-z0-9._/-]/;
|
|
51
|
+
const FENCE_RE = /^\s*(`{3,}|~{3,})/;
|
|
52
|
+
const TRAILING_PUNCT_RE = /[.,;:]+$/;
|
|
53
|
+
/** A citation's final segment must look like \u0060name.ext\u0060: a bare \u0060.\u0060 or a dotless
|
|
54
|
+
* segment is a directory mention, not a file. */
|
|
55
|
+
const FILE_SEGMENT_RE = /^[^.].*\.[^.]+$/;
|
|
56
|
+
const FRAGMENT_RE = /^#([A-Za-z0-9._-]+)/;
|
|
57
|
+
/** Whether the token starting at `start` is the argument of a shell command. */
|
|
58
|
+
function isProseCommand(line, start) {
|
|
59
|
+
const head = line.slice(0, start).trimEnd();
|
|
60
|
+
if (head === "") return false;
|
|
61
|
+
const word = head.split(/\s+/).pop() ?? "";
|
|
62
|
+
return PROSE_COMMAND_PREFIXES.includes(word);
|
|
63
|
+
}
|
|
64
|
+
/** The token's final path segment (`references/a/b.md` -> `b.md`). */
|
|
65
|
+
function lastSegmentOf(target) {
|
|
66
|
+
return target.slice(target.lastIndexOf("/") + 1);
|
|
67
|
+
}
|
|
68
|
+
/** The token's parent directory within the skill (`references/a/b.md` -> `references/a`). */
|
|
69
|
+
function parentDirOf(target) {
|
|
70
|
+
const cut = target.lastIndexOf("/");
|
|
71
|
+
return cut <= 0 ? "" : target.slice(0, cut);
|
|
72
|
+
}
|
|
73
|
+
/** Classify one token by its first path segment. */
|
|
74
|
+
function classifyToken(token) {
|
|
75
|
+
const head = token.split("/")[0] ?? "";
|
|
76
|
+
return CITATION_SUPPORT_DIRS.includes(head) ? "citation" : "foreign";
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Resolve every path-shaped token in `content`.
|
|
80
|
+
* @param input - content, the skill-root-relative path of its owner, the skill's
|
|
81
|
+
* file list, and an optional scan budget.
|
|
82
|
+
* @returns the refs plus the dangling and foreign subsets; `truncated` marks a
|
|
83
|
+
* report that stopped at the budget.
|
|
84
|
+
*/
|
|
85
|
+
function resolveCitations(input) {
|
|
86
|
+
const budget = input.budget ?? 500;
|
|
87
|
+
const files = new Set(input.files.map((path) => path.replace(/\\/g, "/")));
|
|
88
|
+
const refs = [];
|
|
89
|
+
const seen = /* @__PURE__ */ new Set();
|
|
90
|
+
let truncated = false;
|
|
91
|
+
let fence = null;
|
|
92
|
+
const lines = input.content.split("\n");
|
|
93
|
+
for (let index = 0; index < lines.length && !truncated; index += 1) {
|
|
94
|
+
const rawLine = lines[index] ?? "";
|
|
95
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
96
|
+
const fenceMark = FENCE_RE.exec(line);
|
|
97
|
+
if (fenceMark) {
|
|
98
|
+
const marker = fenceMark[1] ?? "";
|
|
99
|
+
fence = fence === null ? marker.slice(0, 1) : null;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
for (const match of line.matchAll(TOKEN_RE)) {
|
|
103
|
+
const matched = match[0];
|
|
104
|
+
const matchedAt = match.index;
|
|
105
|
+
let start = matchedAt;
|
|
106
|
+
while (start > 0 && TOKEN_CHAR_RE.test(line[start - 1] ?? "")) start -= 1;
|
|
107
|
+
const prefix = line.slice(0, start);
|
|
108
|
+
const tail = line.slice(matchedAt + matched.length);
|
|
109
|
+
const fragment = FRAGMENT_RE.exec(tail)?.[1];
|
|
110
|
+
const token = matched.replace(TRAILING_PUNCT_RE, "");
|
|
111
|
+
const scanned = line.slice(start, matchedAt + matched.length);
|
|
112
|
+
const classified = fence !== null ? "fence" : prefix.endsWith(":") && line.slice(start, start + 2) === "//" ? "url" : isProseCommand(line, start) ? "prose" : classifyToken(scanned);
|
|
113
|
+
const namesFile = !scanned.split("/").includes("..") && (FILE_SEGMENT_RE.test(lastSegmentOf(scanned)) || files.has(token));
|
|
114
|
+
const kind = classified === "citation" && !namesFile ? "prose" : classified;
|
|
115
|
+
const target = kind === "citation" ? token : null;
|
|
116
|
+
const key = `${index}|${kind}|${target ?? token}`;
|
|
117
|
+
if (seen.has(key)) continue;
|
|
118
|
+
seen.add(key);
|
|
119
|
+
refs.push({
|
|
120
|
+
raw: token,
|
|
121
|
+
line: index + 1,
|
|
122
|
+
target,
|
|
123
|
+
base: "root",
|
|
124
|
+
kind,
|
|
125
|
+
exists: target !== null && files.has(target),
|
|
126
|
+
...fragment === void 0 ? {} : { fragment }
|
|
127
|
+
});
|
|
128
|
+
if (refs.length >= budget) {
|
|
129
|
+
truncated = true;
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const citations = refs.filter((ref) => ref.kind === "citation");
|
|
135
|
+
const undecidable = (ref) => {
|
|
136
|
+
const target = ref.target;
|
|
137
|
+
return target !== null && !ref.exists && files.has(parentDirOf(target));
|
|
138
|
+
};
|
|
139
|
+
return {
|
|
140
|
+
refs,
|
|
141
|
+
dangling: citations.filter((ref) => !ref.exists && !undecidable(ref)),
|
|
142
|
+
unverified: citations.filter(undecidable),
|
|
143
|
+
foreign: refs.filter((ref) => ref.kind !== "citation"),
|
|
144
|
+
truncated
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
/** The sanctioned body hook (design §5.6): a list item whose payload is
|
|
148
|
+
* exactly one support-file path, so the file stays discoverable in the body. */
|
|
149
|
+
const HOOK_LINE_RE = /^- [^\n]{1,60} → ((?:references|templates|scripts|assets)\/[a-z0-9][a-z0-9._/-]*)$/;
|
|
150
|
+
/** The retirement escape hatch (design §5.6): a standalone body comment that
|
|
151
|
+
* names the support file it exempts and the reason it must survive. The path
|
|
152
|
+
* is part of the marker because the proposal list is per FILE, and a reason is
|
|
153
|
+
* required — an unexplained exemption is what this hook exists to prevent. */
|
|
154
|
+
const KEEP_LINE_RE = /^<!--\s*keep:\s*((?:references|templates|scripts|assets)\/[a-z0-9][a-z0-9._/-]*)\s+(\S[^>]*?)\s*-->$/;
|
|
155
|
+
/** Whether a skill-relative path names a FILE rather than a directory: the same
|
|
156
|
+
* rule the scanner applies to a token's final segment (`name.ext`). The support
|
|
157
|
+
* listing is one level deep and includes directory entries (a real library has
|
|
158
|
+
* `references/archive`), which no pointer or retirement list may treat as a file.
|
|
159
|
+
* @param path - a skill-root-relative support path.
|
|
160
|
+
* @returns true when the final segment is file-shaped.
|
|
161
|
+
*/
|
|
162
|
+
function isFileShapedPath(path) {
|
|
163
|
+
return FILE_SEGMENT_RE.test(path.slice(path.lastIndexOf("/") + 1));
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Scan a body for sanctioned hooks and `keep` markers.
|
|
167
|
+
* @param content - the SKILL.md body (frontmatter included).
|
|
168
|
+
* @returns hook targets plus the `keep` reasons keyed by target.
|
|
169
|
+
*/
|
|
170
|
+
function scanBodyHooks(content) {
|
|
171
|
+
const targets = [];
|
|
172
|
+
const seen = /* @__PURE__ */ new Set();
|
|
173
|
+
const kept = /* @__PURE__ */ new Map();
|
|
174
|
+
let fence = null;
|
|
175
|
+
for (const rawLine of content.split("\n")) {
|
|
176
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
177
|
+
const fenceMark = FENCE_RE.exec(line);
|
|
178
|
+
if (fenceMark) {
|
|
179
|
+
fence = fence === null ? (fenceMark[1] ?? "").slice(0, 1) : null;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (fence !== null) continue;
|
|
183
|
+
const keep = KEEP_LINE_RE.exec(line);
|
|
184
|
+
if (keep?.[1] !== void 0) {
|
|
185
|
+
kept.set(keep[1], (keep[2] ?? "").trim());
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const target = HOOK_LINE_RE.exec(line)?.[1];
|
|
189
|
+
if (target === void 0 || seen.has(target)) continue;
|
|
190
|
+
seen.add(target);
|
|
191
|
+
targets.push(target);
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
targets,
|
|
195
|
+
kept
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region lib/types/tool-dispatch.js
|
|
200
|
+
/**
|
|
201
|
+
* The family's ONE reader of platform tool-dispatch events.
|
|
202
|
+
*
|
|
203
|
+
* The platform records a finished tool call under two different event
|
|
204
|
+
* vocabularies and only one of them is written per dispatch, chosen by the
|
|
205
|
+
* mounted tool runtime's mode:
|
|
206
|
+
*
|
|
207
|
+
* - native mode: \`tool/call\` (with \`callId\`) settled by \`tool/result\`, the
|
|
208
|
+
* write sites being core/tools/src/batch.ts:247 and :256.
|
|
209
|
+
* - PTC mode: \`tool/ptc-dispatch-start\` and \`tool/ptc-dispatch\` (with
|
|
210
|
+
* \`subCallId\`), the write sites being core/tool-executor-ptc/src/ptc.ts:577 and :550.
|
|
211
|
+
*
|
|
212
|
+
* A consumer that matches a vocabulary directly therefore goes blind in the
|
|
213
|
+
* other mode while still appearing to work — the defect this module exists to
|
|
214
|
+
* make impossible. Every family consumer reads dispatches through
|
|
215
|
+
* \`ToolDispatchNormalizer\` (or the pure helpers below) and matches on
|
|
216
|
+
* \`ToolDispatchSignal\` fields only; \`verify-arch-guards\` rule N11 rejects a
|
|
217
|
+
* dispatch event-type comparison anywhere else.
|
|
218
|
+
*
|
|
219
|
+
* ## The one-dispatch invariant
|
|
220
|
+
*
|
|
221
|
+
* One dispatch produces exactly one \`ToolDispatchSignal\`, no matter how many
|
|
222
|
+
* events carry it: a start/settle pair for a PTC sub-dispatch, a call/result
|
|
223
|
+
* pair for a native call, or both vocabularies for the same call. Deduplication
|
|
224
|
+
* and outcome folding are keyed by the platform's own per-vocabulary call
|
|
225
|
+
* identity, which is stable across the pair (the platform's event JSDoc:
|
|
226
|
+
* "the pairing ids (matching the \`tool/ptc-dispatch-start\` with the same
|
|
227
|
+
* \`subCallId\`)").
|
|
228
|
+
*
|
|
229
|
+
* ## Layer
|
|
230
|
+
*
|
|
231
|
+
* Cross-cutting normalization: the reader half of the dispatch vocabulary,
|
|
232
|
+
* next to \`signals.ts\` (which folds the signals this module emits). Both are
|
|
233
|
+
* consumers; neither subscribes to the platform bus itself.
|
|
234
|
+
* @module
|
|
235
|
+
*/
|
|
236
|
+
/** The platform event type carrying a PTC sub-dispatch start. */
|
|
237
|
+
const PTC_DISPATCH_START_EVENT = "tool/ptc-dispatch-start";
|
|
238
|
+
/** The platform event type carrying a PTC sub-dispatch settle. */
|
|
239
|
+
const PTC_DISPATCH_EVENT = "tool/ptc-dispatch";
|
|
240
|
+
/** The platform event type carrying a native tool call. */
|
|
241
|
+
const NATIVE_CALL_EVENT = "tool/call";
|
|
242
|
+
/** The platform event type carrying a native tool result. */
|
|
243
|
+
const NATIVE_RESULT_EVENT = "tool/result";
|
|
244
|
+
/**
|
|
245
|
+
* The dispatch vocabulary this module owns. A consumer must never compare
|
|
246
|
+
* against these literals itself (rule N11); it compares \`kind\` instead.
|
|
247
|
+
*/
|
|
248
|
+
const DISPATCH_EVENT_TYPES = [
|
|
249
|
+
NATIVE_CALL_EVENT,
|
|
250
|
+
NATIVE_RESULT_EVENT,
|
|
251
|
+
PTC_DISPATCH_START_EVENT,
|
|
252
|
+
PTC_DISPATCH_EVENT
|
|
253
|
+
];
|
|
254
|
+
/**
|
|
255
|
+
* Model-visible session frames: the message types plus the ONE dispatch vocabulary above.
|
|
256
|
+
* Consumers classify through this list instead of naming event literals (rule N11).
|
|
257
|
+
*/
|
|
258
|
+
const MODEL_SESSION_EVENT_TYPES = [
|
|
259
|
+
"user/message",
|
|
260
|
+
"assistant/message",
|
|
261
|
+
...DISPATCH_EVENT_TYPES
|
|
262
|
+
];
|
|
263
|
+
/**
|
|
264
|
+
* \`TypeError\` thrown when a payload that claims to be a dispatch event
|
|
265
|
+
* violates the platform's event declaration. Named so a deployment can tell this
|
|
266
|
+
* refusal apart from a generic failure in a log line.
|
|
267
|
+
*/
|
|
268
|
+
var ToolDispatchPayloadError = class extends TypeError {
|
|
269
|
+
name = "ToolDispatchPayloadError";
|
|
270
|
+
};
|
|
271
|
+
/** The dispatch event types this module recognizes, as a set. */
|
|
272
|
+
const DISPATCH_EVENT_TYPE_SET = new Set(DISPATCH_EVENT_TYPES);
|
|
273
|
+
/** \`name\`-less payloads: an external emitter or a corrupt log can produce these. */
|
|
274
|
+
const MALFORMED = "malformed";
|
|
275
|
+
/** One tool-result block of a native result payload, or \`null\` when the payload carries none. */
|
|
276
|
+
function firstResultBlock(data) {
|
|
277
|
+
const content = data.message?.content;
|
|
278
|
+
if (!Array.isArray(content)) return null;
|
|
279
|
+
for (const entry of content) {
|
|
280
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
281
|
+
const block = entry;
|
|
282
|
+
if (block.type === "tool-result") return block;
|
|
283
|
+
}
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
/** Deterministic identity for a dispatch payload that carries no call id. */
|
|
287
|
+
function payloadIdentity(data) {
|
|
288
|
+
if (data === void 0) return "";
|
|
289
|
+
try {
|
|
290
|
+
return JSON.stringify(data);
|
|
291
|
+
} catch {
|
|
292
|
+
return "";
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** Read the payload of a recognized dispatch event, or \`null\` for any other event. */
|
|
296
|
+
function readDispatchRecord(event) {
|
|
297
|
+
if (!DISPATCH_EVENT_TYPE_SET.has(event.type)) return null;
|
|
298
|
+
const data = event.data ?? {};
|
|
299
|
+
if (event.type === "tool/result") {
|
|
300
|
+
const owner = data.message?.source?.callId;
|
|
301
|
+
const block = firstResultBlock(data);
|
|
302
|
+
const callId = typeof owner === "string" && owner !== "" ? owner : typeof block?.toolCallId === "string" && block.toolCallId !== "" ? block.toolCallId : void 0;
|
|
303
|
+
if (callId === void 0) return null;
|
|
304
|
+
return {
|
|
305
|
+
kind: "native",
|
|
306
|
+
callId,
|
|
307
|
+
rootCallId: callId,
|
|
308
|
+
name: "",
|
|
309
|
+
arguments: void 0,
|
|
310
|
+
outcome: { ok: data.isError !== true && data.error === void 0 && block?.isError !== true }
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
const isPtc = event.type === "tool/ptc-dispatch-start" || event.type === "tool/ptc-dispatch";
|
|
314
|
+
const identity = isPtc ? data.subCallId : data.callId;
|
|
315
|
+
const callId = typeof identity === "string" && identity !== "" ? identity : `${event.type}:${payloadIdentity(event.data)}`;
|
|
316
|
+
const parent = isPtc && typeof data.parentCallId === "string" && data.parentCallId !== "" ? data.parentCallId : void 0;
|
|
317
|
+
const name = typeof data.name === "string" && data.name !== "" ? data.name : MALFORMED;
|
|
318
|
+
return {
|
|
319
|
+
kind: isPtc ? "program" : "native",
|
|
320
|
+
callId,
|
|
321
|
+
rootCallId: typeof data.rootCallId === "string" && data.rootCallId !== "" ? data.rootCallId : parent ?? callId,
|
|
322
|
+
name,
|
|
323
|
+
arguments: data.arguments,
|
|
324
|
+
...isPtc && event.type === "tool/ptc-dispatch" ? { outcome: { ok: data.isError !== true } } : {}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* The ledger key of one dispatch: a scope-qualified call id.
|
|
329
|
+
*
|
|
330
|
+
* v43 audit (FLOW4-4): a normalizer shared by every session (skill-usage's live listener holds ONE
|
|
331
|
+
* process-wide instance) used the bare call id, so two sessions that produced the same id — PTC
|
|
332
|
+
* sub-call ids are short, and an id-less payload falls back to a type+payload key that is not
|
|
333
|
+
* unique by construction — collided: the second session's read was absorbed as "already seen" and
|
|
334
|
+
* never counted, and a settle in one session flipped the other's `ok`. Callers that span sessions
|
|
335
|
+
* pass the session id as `scope`.
|
|
336
|
+
* @param callId - the dispatch's call id (or its payload-derived fallback).
|
|
337
|
+
* @param scope - the owning session id, or '' for a fold that never leaves one session.
|
|
338
|
+
* @returns the key both the ledger and every projection fold dedupe on.
|
|
339
|
+
*/
|
|
340
|
+
function dispatchKeyOf(callId, scope = "") {
|
|
341
|
+
return scope === "" ? callId : `${scope}:${callId}`;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The pure half of the ledger: what one event says about one dispatch.
|
|
345
|
+
*
|
|
346
|
+
* The DECISION (which dispatch, and whether this event is the one that opens it) lives here and
|
|
347
|
+
* only here; carriers differ in what they keep — the class below keeps consumer-visible mutable
|
|
348
|
+
* signals, the family's `evolutionReads`/`evolutionSignals` projection units keep plain-JSON
|
|
349
|
+
* ledgers. `name` is empty on an event that only settles an already-opened dispatch (a native
|
|
350
|
+
* `tool/result`), and `outcome` is present exactly when the event carried one.
|
|
351
|
+
* @param event - one session event; any non-dispatch event answers `null`.
|
|
352
|
+
* @param scope - the owning session id, or '' for a single-session fold.
|
|
353
|
+
* @returns the step, or `null` when the event is not a dispatch.
|
|
354
|
+
*/
|
|
355
|
+
function dispatchStepOf(event, scope = "") {
|
|
356
|
+
const record = readDispatchRecord(event);
|
|
357
|
+
if (record === null) return null;
|
|
358
|
+
return {
|
|
359
|
+
key: dispatchKeyOf(record.callId, scope),
|
|
360
|
+
kind: record.kind,
|
|
361
|
+
callId: record.callId,
|
|
362
|
+
rootCallId: record.rootCallId,
|
|
363
|
+
name: record.name,
|
|
364
|
+
arguments: record.arguments,
|
|
365
|
+
...record.outcome === void 0 ? {} : { outcome: record.outcome }
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* The family's single dispatch ledger: absorbs platform events in log order,
|
|
370
|
+
* emits one \`ToolDispatchSignal\` per dispatch, and folds later events of the
|
|
371
|
+
* same dispatch into the record it already emitted.
|
|
372
|
+
*
|
|
373
|
+
* Consumers keep the \`ToolDispatchSignal\` object they received and re-read it
|
|
374
|
+
* later; no consumer needs to correlate events itself.
|
|
375
|
+
*/
|
|
376
|
+
var ToolDispatchNormalizer = class {
|
|
377
|
+
records = /* @__PURE__ */ new Map();
|
|
378
|
+
/** S2-P2-14: cap for the LEDGER (and the settle markers) — opt-in, meant for
|
|
379
|
+
* the long-lived live listener (skill-usage) whose ledger is pure dedup
|
|
380
|
+
* state and would otherwise grow with the process lifetime. `Infinity` (the
|
|
381
|
+
* default, used by whole-log folding) keeps every dispatch. Eviction is
|
|
382
|
+
* oldest-first: a call/result pair spans one tool call, so an evicted
|
|
383
|
+
* dispatch can never be re-paired within any realistic window. */
|
|
384
|
+
maxTracked;
|
|
385
|
+
/** S2-P2-12: call ids whose outcome has already been reported to the settle
|
|
386
|
+
* channel — a replayed result event must not settle the same dispatch twice. */
|
|
387
|
+
settledIds = /* @__PURE__ */ new Set();
|
|
388
|
+
constructor(options = {}) {
|
|
389
|
+
this.maxTracked = options.maxTracked ?? Number.POSITIVE_INFINITY;
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Absorb one session event.
|
|
393
|
+
* @param event - the event to absorb; any non-dispatch event is ignored.
|
|
394
|
+
* @returns the dispatch's signal when this event FIRST reveals the dispatch,
|
|
395
|
+
* otherwise \`null\` (the paired event of an already-emitted dispatch, or a
|
|
396
|
+
* non-dispatch event). A \`null\` return is never a dispatch to count again.
|
|
397
|
+
*/
|
|
398
|
+
advance(event, scope = "") {
|
|
399
|
+
const step = dispatchStepOf(event, scope);
|
|
400
|
+
if (step === null) return null;
|
|
401
|
+
const existing = this.records.get(step.key);
|
|
402
|
+
if (existing !== void 0) {
|
|
403
|
+
if (step.outcome !== void 0) existing.ok = step.outcome.ok;
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
if (step.name === "") return null;
|
|
407
|
+
const signal = {
|
|
408
|
+
kind: step.kind,
|
|
409
|
+
callId: step.callId,
|
|
410
|
+
rootCallId: step.rootCallId,
|
|
411
|
+
name: step.name,
|
|
412
|
+
arguments: step.arguments,
|
|
413
|
+
ok: step.outcome?.ok
|
|
414
|
+
};
|
|
415
|
+
this.records.set(step.key, signal);
|
|
416
|
+
this.evict();
|
|
417
|
+
return signal;
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* S2-P2-12: the SETTLE channel. \`advance\` answers \`null\` for the paired
|
|
421
|
+
* event that settles an already-emitted dispatch, so a consumer that must act
|
|
422
|
+
* on the OUTCOME (e.g. count successful skill reads only) cannot tell which
|
|
423
|
+
* dispatch a \`null\` belonged to. Call this with the same event AFTER
|
|
424
|
+
* \`advance\`: it answers the settled dispatch exactly once (replayed settle
|
|
425
|
+
* events answer \`null\`).
|
|
426
|
+
* @param event - the event already absorbed by \`advance\`.
|
|
427
|
+
* @returns the dispatch this event settled, or \`null\`.
|
|
428
|
+
*/
|
|
429
|
+
settledSignalOf(event, scope = "") {
|
|
430
|
+
const step = dispatchStepOf(event, scope);
|
|
431
|
+
if (step?.outcome === void 0) return null;
|
|
432
|
+
if (this.settledIds.has(step.key)) return null;
|
|
433
|
+
const signal = this.records.get(step.key);
|
|
434
|
+
if (signal === void 0) return null;
|
|
435
|
+
this.settledIds.add(step.key);
|
|
436
|
+
this.evict();
|
|
437
|
+
return signal;
|
|
438
|
+
}
|
|
439
|
+
/** Oldest-first eviction once the ledger (or the settle markers) overflows. */
|
|
440
|
+
evict() {
|
|
441
|
+
while (this.records.size > this.maxTracked) {
|
|
442
|
+
const oldest = this.records.keys().next().value;
|
|
443
|
+
if (oldest === void 0) break;
|
|
444
|
+
this.records.delete(oldest);
|
|
445
|
+
this.settledIds.delete(oldest);
|
|
446
|
+
}
|
|
447
|
+
while (this.settledIds.size > this.maxTracked) {
|
|
448
|
+
const oldest = this.settledIds.values().next().value;
|
|
449
|
+
if (oldest === void 0) break;
|
|
450
|
+
this.settledIds.delete(oldest);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
/** Every emitted dispatch, in first-seen order. */
|
|
454
|
+
get signals() {
|
|
455
|
+
return [...this.records.values()];
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Fold every event of a session log, in order.
|
|
459
|
+
* @param events - the log, oldest first.
|
|
460
|
+
* @returns one signal per dispatch, in first-seen order.
|
|
461
|
+
*/
|
|
462
|
+
foldAll(events) {
|
|
463
|
+
const emitted = [];
|
|
464
|
+
for (const event of events) {
|
|
465
|
+
const signal = this.advance(event);
|
|
466
|
+
if (signal !== null) emitted.push(signal);
|
|
467
|
+
}
|
|
468
|
+
return emitted;
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
/**
|
|
472
|
+
* Read one event into a dispatch record without a ledger (the pure half of the
|
|
473
|
+
* fold). Unlike the ledger it does NOT dedupe: a caller that walks a log and
|
|
474
|
+
* emits its own lines needs the call line on the event that opens the result.
|
|
475
|
+
* @param event - one session event; an absent event (an over-advanced index)
|
|
476
|
+
* answers \`null\` rather than throwing.
|
|
477
|
+
* @returns the dispatch this event opens, or \`null\` for any other event.
|
|
478
|
+
*/
|
|
479
|
+
function readDispatchSignal(event) {
|
|
480
|
+
if (event?.type === void 0) return null;
|
|
481
|
+
const record = readDispatchRecord({
|
|
482
|
+
type: event.type,
|
|
483
|
+
...event.data === void 0 ? {} : { data: event.data }
|
|
484
|
+
});
|
|
485
|
+
if (record === null || record.name === "") return null;
|
|
486
|
+
return {
|
|
487
|
+
kind: record.kind,
|
|
488
|
+
callId: record.callId,
|
|
489
|
+
rootCallId: record.rootCallId,
|
|
490
|
+
name: record.name,
|
|
491
|
+
arguments: record.arguments
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
/** Tool names that READ one skill. The single authority for skill-read detection. */
|
|
495
|
+
const SKILL_READ_TOOL_NAMES = new Set(["skill"]);
|
|
496
|
+
/**
|
|
497
|
+
* Is this dispatched tool name a single-skill read?
|
|
498
|
+
* @param name - the dispatched tool name.
|
|
499
|
+
* @returns \`true\` only for the read tool whose arguments name one skill.
|
|
500
|
+
*/
|
|
501
|
+
function isSkillReadToolName(name) {
|
|
502
|
+
return SKILL_READ_TOOL_NAMES.has(name);
|
|
503
|
+
}
|
|
504
|
+
/** Tool names whose dispatch opens a code program, i.e. whose sub-dispatches are \`program\`. */
|
|
505
|
+
const PROGRAM_TOOL_NAMES = new Set(["run_code"]);
|
|
506
|
+
/**
|
|
507
|
+
* Does this signal read one skill, and did it not fail?
|
|
508
|
+
* @param signal - a normalized dispatch.
|
|
509
|
+
* @returns the skill name the dispatch read, or \`undefined\` when the dispatch
|
|
510
|
+
* is not a skill read or has failed. A dispatch whose outcome is still pending
|
|
511
|
+
* counts as a read: the platform settles every started sub-dispatch, so pending
|
|
512
|
+
* is a live-window state, not a failure.
|
|
513
|
+
*/
|
|
514
|
+
/** Tool names whose dispatch reads one FILE — the deployment's file tool
|
|
515
|
+
* (default `read`). A differently named tool is configured, not guessed. */
|
|
516
|
+
const DEFAULT_SUPPORT_READ_TOOL_NAMES = ["read"];
|
|
517
|
+
/** Dispatch arguments: a JSON string in native mode and an already-parsed
|
|
518
|
+
* object in PTC mode (core/tool-executor-ptc/src/types.ts:11-23) — parsed defensively so no
|
|
519
|
+
* consumer has to trust one modality's encoding. */
|
|
520
|
+
function parsedArguments(signal) {
|
|
521
|
+
let parsed = signal.arguments;
|
|
522
|
+
if (typeof parsed === "string") try {
|
|
523
|
+
parsed = JSON.parse(parsed);
|
|
524
|
+
} catch {
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
528
|
+
return parsed;
|
|
529
|
+
}
|
|
530
|
+
/** The path-shaped argument of one already-parsed call, when it carries one. */
|
|
531
|
+
function readPathFromRecord(record) {
|
|
532
|
+
if (record === null) return null;
|
|
533
|
+
for (const key of [
|
|
534
|
+
"file_path",
|
|
535
|
+
"path",
|
|
536
|
+
"file",
|
|
537
|
+
"target"
|
|
538
|
+
]) {
|
|
539
|
+
const value = record[key];
|
|
540
|
+
if (typeof value === "string" && value.trim() !== "") return value;
|
|
541
|
+
}
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
/** The path-shaped argument of a file tool, when it carries one. */
|
|
545
|
+
function readPathArgument(signal) {
|
|
546
|
+
return readPathFromRecord(parsedArguments(signal));
|
|
547
|
+
}
|
|
548
|
+
/** The path one dispatch names, for the read-evidence projection. */
|
|
549
|
+
function dispatchPathOf(step) {
|
|
550
|
+
let parsed = step.arguments;
|
|
551
|
+
if (typeof parsed === "string") try {
|
|
552
|
+
parsed = JSON.parse(parsed);
|
|
553
|
+
} catch {
|
|
554
|
+
return null;
|
|
555
|
+
}
|
|
556
|
+
return parsed !== null && typeof parsed === "object" ? readPathFromRecord(parsed) : null;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Read one dispatch as a SUPPORT-FILE read attributed to a skill: a read of
|
|
560
|
+
* `<root>/<skill>/<support dir>/…` is demand evidence for that one file, the
|
|
561
|
+
* way `skillReadNameOf` is demand evidence for a whole body.
|
|
562
|
+
* @param signal - a settled dispatch.
|
|
563
|
+
* @param options - the deployment's file-tool names and its skills root; an
|
|
564
|
+
* empty root falls back to the `/skills/` marker in the path.
|
|
565
|
+
* @returns the skill name and the skill-root-relative path, or `null` when the
|
|
566
|
+
* dispatch is not a support-file read. Pure: no IO, no service lookup.
|
|
567
|
+
*/
|
|
568
|
+
/** Attribute one raw path string to a skill support file (pure; no IO). */
|
|
569
|
+
function supportFileReadFromPath(raw, options) {
|
|
570
|
+
const normalized = raw.replace(/\\/g, "/").trim();
|
|
571
|
+
if (normalized === "" || normalized.split("/").includes("..")) return null;
|
|
572
|
+
const root = options.root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
573
|
+
let relative = null;
|
|
574
|
+
if (root !== "") {
|
|
575
|
+
const lower = normalized.toLowerCase();
|
|
576
|
+
const lowerRoot = root.toLowerCase();
|
|
577
|
+
if (lower.startsWith(lowerRoot + "/")) relative = normalized.slice(root.length + 1);
|
|
578
|
+
}
|
|
579
|
+
if (relative === null) {
|
|
580
|
+
const at = normalized.toLowerCase().lastIndexOf("/skills/");
|
|
581
|
+
if (at === -1) return null;
|
|
582
|
+
relative = normalized.slice(at + 8);
|
|
583
|
+
}
|
|
584
|
+
const parts = relative.split("/").filter((part) => part !== "");
|
|
585
|
+
const skill = parts[0];
|
|
586
|
+
const dir = parts[1];
|
|
587
|
+
if (skill === void 0 || dir === void 0 || parts.length < 3) return null;
|
|
588
|
+
if (!CITATION_SUPPORT_DIRS.includes(dir)) return null;
|
|
589
|
+
return {
|
|
590
|
+
skill: skill.trim(),
|
|
591
|
+
rel: parts.slice(1).join("/")
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
function supportFileReadOf(signal, options) {
|
|
595
|
+
if (!options.toolNames.includes(signal.name)) return null;
|
|
596
|
+
if (signal.ok === false) return null;
|
|
597
|
+
const raw = readPathArgument(signal);
|
|
598
|
+
return raw === null ? null : supportFileReadFromPath(raw, options);
|
|
599
|
+
}
|
|
600
|
+
function skillReadNameOf(signal) {
|
|
601
|
+
if (!SKILL_READ_TOOL_NAMES.has(signal.name)) return void 0;
|
|
602
|
+
if (signal.ok === false) return void 0;
|
|
603
|
+
const candidate = parsedArguments(signal);
|
|
604
|
+
if (candidate === null) return void 0;
|
|
605
|
+
const name = typeof candidate.name === "string" ? candidate.name : typeof candidate.skill === "string" ? candidate.skill : "";
|
|
606
|
+
return name === "" ? void 0 : name;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Fold one session log into its deduplicated dispatches.
|
|
610
|
+
* @param events - the log, oldest first. Pass an array, not a live snapshot
|
|
611
|
+
* iterator, when the log can grow while folding.
|
|
612
|
+
* @returns one signal per dispatch, in first-seen order.
|
|
613
|
+
*/
|
|
614
|
+
function foldToolDispatches(events) {
|
|
615
|
+
return new ToolDispatchNormalizer().foldAll(events);
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Every skill name this log read through a dispatch, deduplicated by dispatch.
|
|
619
|
+
* @param events - the log, oldest first.
|
|
620
|
+
* @returns the names read by at least one non-failed skill dispatch.
|
|
621
|
+
*/
|
|
622
|
+
function collectReadSkillNames(events) {
|
|
623
|
+
const names = /* @__PURE__ */ new Set();
|
|
624
|
+
for (const signal of foldToolDispatches(events)) {
|
|
625
|
+
const name = skillReadNameOf(signal);
|
|
626
|
+
if (name !== void 0) names.add(name);
|
|
627
|
+
}
|
|
628
|
+
return names;
|
|
629
|
+
}
|
|
630
|
+
/** Every skill support file this log read through a non-failed configured file tool. */
|
|
631
|
+
function collectReadSupportFiles(events, options) {
|
|
632
|
+
const reads = /* @__PURE__ */ new Map();
|
|
633
|
+
for (const signal of foldToolDispatches(events)) {
|
|
634
|
+
const hit = supportFileReadOf(signal, options);
|
|
635
|
+
if (hit === null) continue;
|
|
636
|
+
const set = reads.get(hit.skill) ?? /* @__PURE__ */ new Set();
|
|
637
|
+
set.add(hit.rel);
|
|
638
|
+
reads.set(hit.skill, set);
|
|
639
|
+
}
|
|
640
|
+
return reads;
|
|
641
|
+
}
|
|
642
|
+
/** Tool names that touch the skill library at all — the review's skill-signal set. */
|
|
643
|
+
const SKILL_TOOL_NAMES = new Set([...SKILL_READ_TOOL_NAMES, "skill_manage"]);
|
|
644
|
+
/**
|
|
645
|
+
* Does this dispatched tool name touch the skill library (read or mutate)?
|
|
646
|
+
* @param name - the dispatched tool name.
|
|
647
|
+
* @returns \`true\` for any skill-library tool. This is the review cadence's
|
|
648
|
+
* skill signal, which has always covered reads and writes alike.
|
|
649
|
+
*/
|
|
650
|
+
function isSkillToolName(name) {
|
|
651
|
+
return SKILL_TOOL_NAMES.has(name);
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Does this dispatched tool name open a code program?
|
|
655
|
+
* @param name - the dispatched tool name.
|
|
656
|
+
* @returns \`true\` for the tool whose sub-dispatches are \`program\` kind.
|
|
657
|
+
*/
|
|
658
|
+
function isProgramToolName(name) {
|
|
659
|
+
return PROGRAM_TOOL_NAMES.has(name);
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Assert that a payload really is the dispatch event it claims to be.
|
|
663
|
+
*
|
|
664
|
+
* The normalizer is deliberately lenient (it also folds persisted logs, where a
|
|
665
|
+
* payload may predate the current declaration). S1-E7 (honesty fix): this
|
|
666
|
+
* function is an OPT-IN gate — NO production consumer calls it; the shipped
|
|
667
|
+
* listeners fold tolerant (`'malformed'` synthesis) precisely because a
|
|
668
|
+
* throwing gate wired into every session event would brick the family on any
|
|
669
|
+
* upstream payload drift. Deployments that want fail-loud behavior call this
|
|
670
|
+
* from their own `session/event` listener. It never silently downgrades: an
|
|
671
|
+
* unrecognized event type or a payload missing a declared field throws a named
|
|
672
|
+
* \`ToolDispatchPayloadError\`.
|
|
673
|
+
* @param event - the session event to check.
|
|
674
|
+
* @returns nothing; throws when the payload violates the platform declaration.
|
|
675
|
+
*/
|
|
676
|
+
function assertDispatchPayload(event) {
|
|
677
|
+
const data = event.data ?? {};
|
|
678
|
+
if (event.type === "tool/call") {
|
|
679
|
+
if (typeof data.name !== "string" || data.name === "" || typeof data.callId !== "string" || data.callId === "") throw new ToolDispatchPayloadError("tool/call carries no name/callId: the agent-loop write site is broken");
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (event.type === "tool/ptc-dispatch-start" || event.type === "tool/ptc-dispatch") {
|
|
683
|
+
if (typeof data.subCallId !== "string" || data.subCallId === "" || typeof data.name !== "string" || data.name === "") throw new ToolDispatchPayloadError(`${event.type} carries no name/subCallId: the PTC bridge write site is broken`);
|
|
684
|
+
if (event.type === "tool/ptc-dispatch" && typeof data.isError !== "boolean") throw new ToolDispatchPayloadError("tool/ptc-dispatch carries no boolean isError: the settle outcome is unusable");
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
if (event.type === "tool/result") return;
|
|
688
|
+
throw new ToolDispatchPayloadError(`${event.type} is not a platform dispatch event; compare signal.kind instead of event types`);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Total dispatches in a log, deduplicated.
|
|
692
|
+
* @param events - the log, oldest first.
|
|
693
|
+
* @returns the number of distinct dispatches, one per dispatch regardless of
|
|
694
|
+
* how many events carried it.
|
|
695
|
+
*/
|
|
696
|
+
function countDispatches(events) {
|
|
697
|
+
return foldToolDispatches(events).length;
|
|
698
|
+
}
|
|
699
|
+
//#endregion
|
|
700
|
+
//#region lib/types/signals.js
|
|
701
|
+
/**
|
|
702
|
+
* Deterministic review signal gate.
|
|
703
|
+
*
|
|
704
|
+
* Scans a DSH session event log for durable learning signals before any LLM
|
|
705
|
+
* is spent. `turn/end` calls `observeEvent`; the returned review kind is
|
|
706
|
+
* accumulated until a configured interval fires.
|
|
707
|
+
*/
|
|
708
|
+
const CORRECTION_PATTERNS = [
|
|
709
|
+
/(?:don'?t|do not|stop|never)\s+(?:do|use|format|explain|write|say)/i,
|
|
710
|
+
/(?:too|very|way\s+too)\s+(?:verbose|long|detailed|short|brief)/i,
|
|
711
|
+
/(?:I|we)\s+(?:prefer|like|want|need)\b/i,
|
|
712
|
+
/remember\s+(?:this|that|to)/i
|
|
713
|
+
];
|
|
714
|
+
const FIX_PATTERNS = [/worked after|fixed by|the fix was|root cause/i, /retry(?:ing)? worked|workaround/i];
|
|
715
|
+
/** Text of one persisted content block, or `''` for any other shape.
|
|
716
|
+
*
|
|
717
|
+
* Content blocks cross the durable session-log boundary, so their runtime
|
|
718
|
+
* shape is `unknown` even where the static event type promises
|
|
719
|
+
* `{ type, text }`: a persisted `content: [null]` (A2-7, v18) used to throw a
|
|
720
|
+
* TypeError here and the review catch swallowed the whole turn's remaining
|
|
721
|
+
* signals. Keeping the guard in one helper also keeps the branches free of
|
|
722
|
+
* conditions the static type already excludes.
|
|
723
|
+
* @param block - one element of a persisted message `content` array.
|
|
724
|
+
* @returns the block's text when it is a text block, otherwise an empty string.
|
|
725
|
+
*/
|
|
726
|
+
function textOfBlock(block) {
|
|
727
|
+
if (block === null || typeof block !== "object") return "";
|
|
728
|
+
const candidate = block;
|
|
729
|
+
return candidate.type === "text" && typeof candidate.text === "string" ? candidate.text : "";
|
|
730
|
+
}
|
|
731
|
+
/** The empty turn-window fold state. */
|
|
732
|
+
function initialTurnFold() {
|
|
733
|
+
return {
|
|
734
|
+
substantive: false,
|
|
735
|
+
toolCalls: 0,
|
|
736
|
+
userChars: 0,
|
|
737
|
+
assistantChars: 0,
|
|
738
|
+
memorySignal: false,
|
|
739
|
+
skillSignal: false,
|
|
740
|
+
opened: []
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Fold ONE session event into a turn-window state, purely.
|
|
745
|
+
*
|
|
746
|
+
* The one fold behind all three readers: `observeEvent` (the mutating face the live `turn/end`
|
|
747
|
+
* path uses), `foldTurn` (a whole-log window fold, kept for structural test sessions) and the
|
|
748
|
+
* family's `evolutionSignals` projection unit. P1-1/N4 guards stay: events arrive from disk, so
|
|
749
|
+
* a persisted `data: null` / non-object or a malformed `content` skips instead of throwing.
|
|
750
|
+
* @param state - the window so far.
|
|
751
|
+
* @param event - the next committed session event.
|
|
752
|
+
* @returns the next state; the same reference when the event carries nothing this fold reads.
|
|
753
|
+
*/
|
|
754
|
+
function foldTurnEvent(state, event) {
|
|
755
|
+
const data = event.data;
|
|
756
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) return state;
|
|
757
|
+
if (event.type === "user/message") {
|
|
758
|
+
const content = data.content;
|
|
759
|
+
if (!Array.isArray(content)) return state;
|
|
760
|
+
const text = content.map(textOfBlock).join(" ");
|
|
761
|
+
return {
|
|
762
|
+
...state,
|
|
763
|
+
userChars: state.userChars + text.length,
|
|
764
|
+
memorySignal: state.memorySignal || CORRECTION_PATTERNS.some((pattern) => pattern.test(text)),
|
|
765
|
+
skillSignal: state.skillSignal || FIX_PATTERNS.some((pattern) => pattern.test(text))
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
if (event.type === "assistant/message") {
|
|
769
|
+
const message = data.message;
|
|
770
|
+
if (!message || !Array.isArray(message.content)) return state;
|
|
771
|
+
const text = message.content.map(textOfBlock).join(" ");
|
|
772
|
+
return {
|
|
773
|
+
...state,
|
|
774
|
+
assistantChars: state.assistantChars + text.length
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
const dispatch = dispatchStepOf(event);
|
|
778
|
+
if (dispatch === null || dispatch.name === "" || state.opened.includes(dispatch.key)) return state;
|
|
779
|
+
let toolCalls = state.toolCalls;
|
|
780
|
+
if (dispatch.kind !== "program") toolCalls += 1;
|
|
781
|
+
return {
|
|
782
|
+
...state,
|
|
783
|
+
opened: [...state.opened, dispatch.key],
|
|
784
|
+
toolCalls,
|
|
785
|
+
skillSignal: state.skillSignal || isSkillToolName(dispatch.name)
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Per-turn dispatch ledgers, keyed by the signal object they feed.
|
|
790
|
+
*
|
|
791
|
+
* `observeEvent` folds ONE event at a time, so the ledger has to outlive the call. One WeakMap
|
|
792
|
+
* entry per `TurnSignals`, so a finished fold's ledger is collectable with the fold itself and two
|
|
793
|
+
* concurrent turns never share one.
|
|
794
|
+
*/
|
|
795
|
+
const dispatchLedgers = /* @__PURE__ */ new WeakMap();
|
|
796
|
+
/** The ledger of the turn this signal is folding; empty before its first dispatch. */
|
|
797
|
+
function ledgerForSignal(signal) {
|
|
798
|
+
return dispatchLedgers.get(signal) ?? [];
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Fold one session event into the current turn observation (the mutating face of
|
|
802
|
+
* {@link foldTurnEvent}: every reader shares the one fold, this one copies the result back onto
|
|
803
|
+
* the caller's signal object and keeps its ledger for the next event).
|
|
804
|
+
* @param signal - the turn observation to advance.
|
|
805
|
+
* @param event - the next committed session event.
|
|
806
|
+
*/
|
|
807
|
+
function observeEvent(signal, event) {
|
|
808
|
+
const next = foldTurnEvent({
|
|
809
|
+
...signal,
|
|
810
|
+
opened: [...ledgerForSignal(signal)]
|
|
811
|
+
}, event);
|
|
812
|
+
signal.substantive = next.substantive;
|
|
813
|
+
signal.toolCalls = next.toolCalls;
|
|
814
|
+
signal.userChars = next.userChars;
|
|
815
|
+
signal.assistantChars = next.assistantChars;
|
|
816
|
+
signal.memorySignal = next.memorySignal;
|
|
817
|
+
signal.skillSignal = next.skillSignal;
|
|
818
|
+
dispatchLedgers.set(signal, next.opened);
|
|
819
|
+
}
|
|
820
|
+
/** Compute review cadence after `turn/end`. */
|
|
821
|
+
function advanceReview(state, turn, signal, config) {
|
|
822
|
+
if (turn === state.lastTurn) return null;
|
|
823
|
+
state.lastTurn = turn;
|
|
824
|
+
signal.substantive = signal.toolCalls >= config.substantiveMinToolCalls || signal.userChars >= config.substantiveMinUserChars || signal.assistantChars >= config.substantiveMinAgentChars;
|
|
825
|
+
if (!signal.substantive) return null;
|
|
826
|
+
state.turnsSinceMemory += signal.memorySignal ? 1 : Math.max(1, signal.toolCalls);
|
|
827
|
+
state.turnsSinceSkill += signal.skillSignal ? 1 : Math.max(1, signal.toolCalls);
|
|
828
|
+
const memoryDue = state.turnsSinceMemory >= config.memoryInterval;
|
|
829
|
+
const skillDue = state.turnsSinceSkill >= config.skillInterval;
|
|
830
|
+
const zero = () => {
|
|
831
|
+
state.turnsSinceMemory = 0;
|
|
832
|
+
state.turnsSinceSkill = 0;
|
|
833
|
+
};
|
|
834
|
+
if (memoryDue && skillDue) {
|
|
835
|
+
if (config.resetOnFire !== false) zero();
|
|
836
|
+
return "combined";
|
|
837
|
+
}
|
|
838
|
+
if (memoryDue) {
|
|
839
|
+
if (config.resetOnFire !== false) state.turnsSinceMemory = 0;
|
|
840
|
+
return "memory";
|
|
841
|
+
}
|
|
842
|
+
if (skillDue) {
|
|
843
|
+
if (config.resetOnFire !== false) state.turnsSinceSkill = 0;
|
|
844
|
+
return "skill";
|
|
845
|
+
}
|
|
846
|
+
return null;
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* Fold a log slice into one turn window, purely.
|
|
850
|
+
*
|
|
851
|
+
* The whole-log reference for {@link foldTurnEvent}: a caller that holds events (a fixture, a
|
|
852
|
+
* structural view, a replay) reads a window without touching a platform Session. Production reads
|
|
853
|
+
* the same window live from the family's `evolutionSignals` projection (`sessionTurnSignals`),
|
|
854
|
+
* which folds `foldTurnEvent` once per committed event.
|
|
855
|
+
* @param events - the log, oldest first. Pass an array, not a live iterator, when it can grow.
|
|
856
|
+
* @param fromSeq - index of the first event of the window (0 for the whole log).
|
|
857
|
+
* @returns the window's signals.
|
|
858
|
+
*/
|
|
859
|
+
function foldTurnEvents(events, fromSeq = 0) {
|
|
860
|
+
const list = [...events];
|
|
861
|
+
let state = initialTurnFold();
|
|
862
|
+
for (let index = Math.max(0, fromSeq); index < list.length; index += 1) {
|
|
863
|
+
const event = list[index];
|
|
864
|
+
if (event) state = foldTurnEvent(state, event);
|
|
865
|
+
}
|
|
866
|
+
const { substantive, toolCalls, userChars, assistantChars, memorySignal, skillSignal } = state;
|
|
867
|
+
return {
|
|
868
|
+
substantive,
|
|
869
|
+
toolCalls,
|
|
870
|
+
userChars,
|
|
871
|
+
assistantChars,
|
|
872
|
+
memorySignal,
|
|
873
|
+
skillSignal
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
//#endregion
|
|
877
|
+
//#region lib/types/evidence.js
|
|
878
|
+
/**
|
|
879
|
+
* Which session frames are EVIDENCE, and which are bookkeeping.
|
|
880
|
+
*
|
|
881
|
+
* The session's evidence index answers "does this seq carry content"; a bare range check used
|
|
882
|
+
* to accept any integer inside the authoring window. A boundary frame satisfies that while carrying
|
|
883
|
+
* nothing a claim can rest on: the `turn/start` seq is the frame a claim about that turn was
|
|
884
|
+
* most likely read out of, and citing it is indistinguishable from citing a real exchange. This
|
|
885
|
+
* module owns the ONE classification of a session frame by what it CARRIES, so the plan path can
|
|
886
|
+
* report an op whose whole citation list is bookkeeping (design
|
|
887
|
+
* `dsh-evolution-skill-history-design.md` §3D, phase 1: report only — no op is refused here).
|
|
888
|
+
*
|
|
889
|
+
* The classification is a DENY list of the pure bookends, not an allow list of content frames.
|
|
890
|
+
* The platform's own vocabulary (`KNOWN_SESSION_EVENT_TYPES`, 57 members at 0.1.5-rc.2) mixes
|
|
891
|
+
* content frames with state-change frames, and out-of-repo plugins append types the family cannot
|
|
892
|
+
* enumerate; an unknown frame is therefore treated as carrying content, because a report that
|
|
893
|
+
* fires on an unclassifiable frame is a false positive and phase 1 exists to measure how many TRUE
|
|
894
|
+
* ones there are. Tightening — a narrower definition, or an allow list built from the platform's
|
|
895
|
+
* vocabulary — changes this table and nothing else (`evidenceKindIndex` is the only reader).
|
|
896
|
+
* @module @lmzhen/dsh-evolution-core
|
|
897
|
+
*/
|
|
898
|
+
/** The frame types that record a boundary and carry no content: the turn and step bookends. */
|
|
899
|
+
const BOOKKEEPING_FRAME_TYPES = new Set([
|
|
900
|
+
"turn/start",
|
|
901
|
+
"turn/end",
|
|
902
|
+
"step/start",
|
|
903
|
+
"step/end"
|
|
904
|
+
]);
|
|
905
|
+
/**
|
|
906
|
+
* Whether one frame type records a boundary and carries no content.
|
|
907
|
+
*
|
|
908
|
+
* The classification table's SECOND reader: the live projection unit
|
|
909
|
+
* (`session-projection.ts`) folds the same answer per event, so the rule stays one table.
|
|
910
|
+
* @param type - a platform session-event type.
|
|
911
|
+
* @returns true for the turn/step bookends.
|
|
912
|
+
*/
|
|
913
|
+
function isBookkeepingFrame(type) {
|
|
914
|
+
return BOOKKEEPING_FRAME_TYPES.has(type);
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* The seqs of the frames that carry content.
|
|
918
|
+
*
|
|
919
|
+
* @param events - the session's frames, oldest first (any iterable; nothing is retained).
|
|
920
|
+
* @returns the substantive seqs, or `undefined` when NO frame carried a usable seq. The two
|
|
921
|
+
* answers are different facts: an empty SET says "every sequenced frame is a boundary", while
|
|
922
|
+
* `undefined` says "this log cannot tell a boundary from a message" (a stub session in a test,
|
|
923
|
+
* a composition whose events carry no seq). A caller that cannot classify must stay silent
|
|
924
|
+
* rather than report every op — the same three-state posture as `sessionReadSkillNames`.
|
|
925
|
+
*/
|
|
926
|
+
function evidenceKindIndex(events) {
|
|
927
|
+
const substantive = /* @__PURE__ */ new Set();
|
|
928
|
+
let sequenced = 0;
|
|
929
|
+
for (const event of events) {
|
|
930
|
+
const seq = event.seq;
|
|
931
|
+
if (typeof seq !== "number" || !Number.isInteger(seq)) continue;
|
|
932
|
+
sequenced += 1;
|
|
933
|
+
if (typeof event.type === "string" && BOOKKEEPING_FRAME_TYPES.has(event.type)) continue;
|
|
934
|
+
substantive.add(seq);
|
|
935
|
+
}
|
|
936
|
+
return sequenced === 0 ? void 0 : substantive;
|
|
937
|
+
}
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region lib/types/session-projection.js
|
|
940
|
+
/**
|
|
941
|
+
* The family's session projections: the per-session facts the family used to re-read the log for.
|
|
942
|
+
*
|
|
943
|
+
* 0.2.x deprecates the synchronous log reads (`Session.snapshotEvents` — "existing logic may
|
|
944
|
+
* remain unmigrated for now, but new calls are prohibited",
|
|
945
|
+
* `core/session/src/index.ts:639-658`) and drives DOMAIN-OWNED units instead: a registered unit
|
|
946
|
+
* folds every committed event once, the runtime service owns the handle and the registry, and a
|
|
947
|
+
* reader asks that service for the current state. Each unit here carries exactly what one pure
|
|
948
|
+
* family reader derives from a log, so that reader keeps its pure form and gains a
|
|
949
|
+
* projection-backed one beside it.
|
|
950
|
+
*
|
|
951
|
+
* State stays bounded. The evidence unit keeps the SPARSE boundary seqs and answers the dense
|
|
952
|
+
* question by complement: a content-seq set grows with every session event, while a turn/step
|
|
953
|
+
* boundary set grows four entries per turn.
|
|
954
|
+
*
|
|
955
|
+
* The registry is part of the platform's BASE bundle (`packages/bundle/base/cordis.patch.yml:158`),
|
|
956
|
+
* so a real host always has it; a composition without it keeps loading (`ctx.inject` probe) and
|
|
957
|
+
* its readers report "cannot classify" instead of guessing — the same posture the pure readers
|
|
958
|
+
* document for a log with no seq.
|
|
959
|
+
* @module @lmzhen/dsh-evolution-core
|
|
960
|
+
*/
|
|
961
|
+
const MAX_TIMESTAMP_MS = 864e13;
|
|
962
|
+
const activityStateSchema = z.object({ lastEventTime: z.number().nonnegative().max(MAX_TIMESTAMP_MS) }).strict();
|
|
963
|
+
const evidenceStateSchema = z.object({
|
|
964
|
+
sequenced: z.number().int().nonnegative(),
|
|
965
|
+
through: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
|
|
966
|
+
bookkeeping: z.array(z.number().int().nonnegative())
|
|
967
|
+
}).strict();
|
|
968
|
+
/** The `evolutionActivity` unit (host-only: no client view is registered for it). */
|
|
969
|
+
const evolutionActivityProjection = {
|
|
970
|
+
key: "evolutionActivity",
|
|
971
|
+
stateVersion: 1,
|
|
972
|
+
stateSchema: activityStateSchema,
|
|
973
|
+
init: () => ({ lastEventTime: 0 }),
|
|
974
|
+
apply: (state, event) => {
|
|
975
|
+
const time = typeof event.time === "number" ? event.time : state.lastEventTime;
|
|
976
|
+
return time === state.lastEventTime ? state : { lastEventTime: time };
|
|
977
|
+
}
|
|
978
|
+
};
|
|
979
|
+
/** The `evolutionEvidence` unit (host-only: no client view is registered for it). */
|
|
980
|
+
const evolutionEvidenceProjection = {
|
|
981
|
+
key: "evolutionEvidence",
|
|
982
|
+
stateVersion: 1,
|
|
983
|
+
stateSchema: evidenceStateSchema,
|
|
984
|
+
init: () => ({
|
|
985
|
+
sequenced: 0,
|
|
986
|
+
through: -1,
|
|
987
|
+
bookkeeping: []
|
|
988
|
+
}),
|
|
989
|
+
apply: (state, event) => {
|
|
990
|
+
const seq = event.seq;
|
|
991
|
+
if (typeof seq !== "number" || !Number.isInteger(seq)) return state;
|
|
992
|
+
const sequenced = state.sequenced + 1;
|
|
993
|
+
const through = seq > state.through ? seq : state.through;
|
|
994
|
+
if (typeof event.type !== "string" || !isBookkeepingFrame(event.type)) return {
|
|
995
|
+
sequenced,
|
|
996
|
+
through,
|
|
997
|
+
bookkeeping: state.bookkeeping
|
|
998
|
+
};
|
|
999
|
+
return {
|
|
1000
|
+
sequenced,
|
|
1001
|
+
through,
|
|
1002
|
+
bookkeeping: [...state.bookkeeping, seq]
|
|
1003
|
+
};
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
/**
|
|
1007
|
+
* Whether one session object can be projected at all.
|
|
1008
|
+
*
|
|
1009
|
+
* The family's readers also take STRUCTURAL session views — `skill-reads.ts` documents the tool
|
|
1010
|
+
* path's bare stub — while the registry folds a session's own log (`snapshotEvents(from, to)`,
|
|
1011
|
+
* `eventAt(seq)`, `seq`, `inheritedEventCount`) whenever it has to build or advance a cell. A
|
|
1012
|
+
* view without those members has no projection state to read, and asking for one would fold a
|
|
1013
|
+
* log the unit cannot index.
|
|
1014
|
+
* @param session - the value a caller holds as its session.
|
|
1015
|
+
* @returns true when the registry can fold this object.
|
|
1016
|
+
*/
|
|
1017
|
+
function isProjectableSession(session) {
|
|
1018
|
+
if (session === null || typeof session !== "object") return false;
|
|
1019
|
+
const candidate = session;
|
|
1020
|
+
const folds = typeof candidate.eventAt === "function";
|
|
1021
|
+
const logs = typeof candidate.snapshotEvents === "function";
|
|
1022
|
+
return folds && logs && typeof candidate.seq === "number";
|
|
1023
|
+
}
|
|
1024
|
+
const projectionHistorySchema = z.object({
|
|
1025
|
+
catalogs: z.array(z.object({
|
|
1026
|
+
text: z.string(),
|
|
1027
|
+
entries: z.array(z.object({
|
|
1028
|
+
name: z.string(),
|
|
1029
|
+
description: z.string()
|
|
1030
|
+
}).strict()).max(512),
|
|
1031
|
+
update: z.boolean()
|
|
1032
|
+
}).strict()).max(8),
|
|
1033
|
+
digests: z.array(z.string()).max(64)
|
|
1034
|
+
}).strict();
|
|
1035
|
+
const readsStateSchema = z.object({ reads: z.array(z.object({
|
|
1036
|
+
key: z.string(),
|
|
1037
|
+
skill: z.string().nullable(),
|
|
1038
|
+
failed: z.boolean(),
|
|
1039
|
+
file: z.string().nullable().optional(),
|
|
1040
|
+
tool: z.string().optional()
|
|
1041
|
+
}).strict()) }).strict();
|
|
1042
|
+
const signalsStateSchema = z.object({
|
|
1043
|
+
through: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
|
|
1044
|
+
lastEventTime: z.number().nonnegative().max(MAX_TIMESTAMP_MS),
|
|
1045
|
+
turnStartSeq: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
|
|
1046
|
+
turn: z.object({
|
|
1047
|
+
substantive: z.boolean(),
|
|
1048
|
+
toolCalls: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
1049
|
+
userChars: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
1050
|
+
assistantChars: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
1051
|
+
memorySignal: z.boolean(),
|
|
1052
|
+
skillSignal: z.boolean(),
|
|
1053
|
+
opened: z.array(z.string())
|
|
1054
|
+
}).strict()
|
|
1055
|
+
}).strict();
|
|
1056
|
+
/** The `evolutionProjectionHistory` unit (host-only). */
|
|
1057
|
+
const evolutionProjectionHistoryProjection = {
|
|
1058
|
+
key: "evolutionProjectionHistory",
|
|
1059
|
+
stateVersion: 1,
|
|
1060
|
+
stateSchema: projectionHistorySchema,
|
|
1061
|
+
init: () => ({
|
|
1062
|
+
catalogs: [],
|
|
1063
|
+
digests: []
|
|
1064
|
+
}),
|
|
1065
|
+
apply: (state, event) => {
|
|
1066
|
+
const frame = event;
|
|
1067
|
+
if (frame.type !== "user/message" || typeof frame.data !== "object" || frame.data === null) return state;
|
|
1068
|
+
const message = frame.data;
|
|
1069
|
+
const source = message.source;
|
|
1070
|
+
if (source === void 0 || typeof source !== "object") return state;
|
|
1071
|
+
if (source.kind === "evolution-skill-projection" && typeof source.digest === "string") {
|
|
1072
|
+
if (state.digests.includes(source.digest)) return state;
|
|
1073
|
+
return {
|
|
1074
|
+
catalogs: state.catalogs,
|
|
1075
|
+
digests: [...state.digests, source.digest].slice(-64)
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
if (source.kind !== "skill-catalog" || source.form !== "catalog" || !Array.isArray(source.entries)) return state;
|
|
1079
|
+
if (!Array.isArray(message.content)) return state;
|
|
1080
|
+
const text = message.content.map((block) => block !== null && typeof block === "object" && block.type === "text" ? String(block.text ?? "") : "").join("");
|
|
1081
|
+
if (!text.includes("<available_skills>") || !text.includes("</available_skills>")) return state;
|
|
1082
|
+
const entries = source.entries.filter((entry) => entry !== null && typeof entry === "object" && typeof entry.name === "string" && typeof entry.description === "string").map((entry) => ({
|
|
1083
|
+
name: entry.name,
|
|
1084
|
+
description: entry.description
|
|
1085
|
+
}));
|
|
1086
|
+
return {
|
|
1087
|
+
catalogs: [...state.catalogs, {
|
|
1088
|
+
text,
|
|
1089
|
+
entries,
|
|
1090
|
+
update: source.update === true
|
|
1091
|
+
}].slice(-8),
|
|
1092
|
+
digests: state.digests
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
/** The `evolutionReads` unit (host-only: no client view is registered for it). */
|
|
1097
|
+
const evolutionReadsProjection = {
|
|
1098
|
+
key: "evolutionReads",
|
|
1099
|
+
stateVersion: 1,
|
|
1100
|
+
stateSchema: readsStateSchema,
|
|
1101
|
+
init: () => ({ reads: [] }),
|
|
1102
|
+
apply: (state, event) => {
|
|
1103
|
+
const step = dispatchStepOf(event);
|
|
1104
|
+
if (step === null) return state;
|
|
1105
|
+
const at = state.reads.findIndex((entry) => entry.key === step.key);
|
|
1106
|
+
const settled = () => {
|
|
1107
|
+
const entry = at < 0 ? void 0 : state.reads[at];
|
|
1108
|
+
if (entry === void 0 || step.outcome === void 0) return state;
|
|
1109
|
+
const failed = !step.outcome.ok;
|
|
1110
|
+
if (entry.failed === failed) return state;
|
|
1111
|
+
const reads = [...state.reads];
|
|
1112
|
+
reads[at] = {
|
|
1113
|
+
key: entry.key,
|
|
1114
|
+
skill: entry.skill,
|
|
1115
|
+
failed,
|
|
1116
|
+
...entry.file === void 0 ? {} : { file: entry.file },
|
|
1117
|
+
...entry.tool === void 0 ? {} : { tool: entry.tool }
|
|
1118
|
+
};
|
|
1119
|
+
return { reads };
|
|
1120
|
+
};
|
|
1121
|
+
if (step.name === "") return settled();
|
|
1122
|
+
if (at >= 0) return settled();
|
|
1123
|
+
const file = dispatchPathOf(step);
|
|
1124
|
+
if (file !== null) return { reads: [...state.reads.slice(-511), {
|
|
1125
|
+
key: step.key,
|
|
1126
|
+
skill: null,
|
|
1127
|
+
failed: step.outcome?.ok === false,
|
|
1128
|
+
file,
|
|
1129
|
+
tool: step.name
|
|
1130
|
+
}] };
|
|
1131
|
+
if (!isSkillReadToolName(step.name)) return state;
|
|
1132
|
+
const skill = skillReadNameOf({
|
|
1133
|
+
kind: step.kind,
|
|
1134
|
+
callId: step.callId,
|
|
1135
|
+
rootCallId: step.rootCallId,
|
|
1136
|
+
name: step.name,
|
|
1137
|
+
arguments: step.arguments,
|
|
1138
|
+
ok: step.outcome?.ok
|
|
1139
|
+
}) ?? null;
|
|
1140
|
+
return { reads: [...state.reads, {
|
|
1141
|
+
key: step.key,
|
|
1142
|
+
skill,
|
|
1143
|
+
failed: step.outcome?.ok === false
|
|
1144
|
+
}] };
|
|
1145
|
+
}
|
|
1146
|
+
};
|
|
1147
|
+
/** The `evolutionSignals` unit (host-only: no client view is registered for it). */
|
|
1148
|
+
const evolutionSignalsProjection = {
|
|
1149
|
+
key: "evolutionSignals",
|
|
1150
|
+
stateVersion: 1,
|
|
1151
|
+
stateSchema: signalsStateSchema,
|
|
1152
|
+
init: () => ({
|
|
1153
|
+
through: -1,
|
|
1154
|
+
lastEventTime: 0,
|
|
1155
|
+
turnStartSeq: -1,
|
|
1156
|
+
turn: initialTurnFold()
|
|
1157
|
+
}),
|
|
1158
|
+
apply: (state, event) => {
|
|
1159
|
+
const start = event.type === "turn/start";
|
|
1160
|
+
const turn = foldTurnEvent(start ? initialTurnFold() : state.turn, event);
|
|
1161
|
+
const seq = typeof event.seq === "number" && Number.isInteger(event.seq) ? event.seq : state.through;
|
|
1162
|
+
const time = typeof event.time === "number" ? event.time : state.lastEventTime;
|
|
1163
|
+
const turnStartSeq = start ? seq : state.turnStartSeq;
|
|
1164
|
+
if (turn === state.turn && seq === state.through && time === state.lastEventTime && turnStartSeq === state.turnStartSeq) return state;
|
|
1165
|
+
return {
|
|
1166
|
+
through: seq,
|
|
1167
|
+
lastEventTime: time,
|
|
1168
|
+
turnStartSeq,
|
|
1169
|
+
turn
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
function projectionService(ctx) {
|
|
1174
|
+
return ctx.get("evolutionProjections");
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Time of one session's newest event, or undefined when the unit is not available.
|
|
1178
|
+
*
|
|
1179
|
+
* The curator's idleness gate reads this instead of folding the session log; undefined is a
|
|
1180
|
+
* measurement that did not happen, which the gate answers with the deployment's fail-open policy.
|
|
1181
|
+
* @param ctx - a context of the runtime (the service is read from the global store).
|
|
1182
|
+
* @param session - the session to ask about.
|
|
1183
|
+
* @returns the newest event's milliseconds, or undefined with no unit or no event.
|
|
1184
|
+
*/
|
|
1185
|
+
function sessionLastEventTime(ctx, session) {
|
|
1186
|
+
if (!isProjectableSession(session)) return void 0;
|
|
1187
|
+
const state = projectionService(ctx)?.activity(session);
|
|
1188
|
+
if (state === void 0 || state.lastEventTime === 0) return void 0;
|
|
1189
|
+
return state.lastEventTime;
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* The skill names one session read through a non-failed dispatch, or undefined when the session
|
|
1193
|
+
* cannot be projected (a structural view, or a host without the runtime service).
|
|
1194
|
+
*
|
|
1195
|
+
* undefined is NOT an empty set: the tool path's read-before-write gate keeps its previous
|
|
1196
|
+
* behavior rather than refusing every write in a composition whose session object is a bare stub.
|
|
1197
|
+
* @param ctx - a context of the runtime.
|
|
1198
|
+
* @param session - the session whose reads are wanted.
|
|
1199
|
+
* @returns the names read, or undefined when the log cannot be folded.
|
|
1200
|
+
*/
|
|
1201
|
+
function sessionReadNames(ctx, session) {
|
|
1202
|
+
if (!isProjectableSession(session)) return void 0;
|
|
1203
|
+
const state = projectionService(ctx)?.reads(session);
|
|
1204
|
+
if (state === void 0) return void 0;
|
|
1205
|
+
const names = /* @__PURE__ */ new Set();
|
|
1206
|
+
for (const entry of state.reads) if (!entry.failed && entry.skill !== null) names.add(entry.skill);
|
|
1207
|
+
return names;
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* The open turn's window signals, or undefined when the session cannot be projected.
|
|
1211
|
+
*
|
|
1212
|
+
* The window is the events since the newest turn/start, folded by the same foldTurnEvent
|
|
1213
|
+
* observeEvent uses; undefined means the caller has no measurement (a structural view), not
|
|
1214
|
+
* that the turn was empty.
|
|
1215
|
+
* @param ctx - a context of the runtime.
|
|
1216
|
+
* @param session - the session whose open turn is being judged.
|
|
1217
|
+
* @returns the window signals, or undefined when the log cannot be folded.
|
|
1218
|
+
*/
|
|
1219
|
+
function sessionTurnSignals(ctx, session) {
|
|
1220
|
+
if (!isProjectableSession(session)) return void 0;
|
|
1221
|
+
const state = projectionService(ctx)?.signals(session);
|
|
1222
|
+
if (state === void 0) return void 0;
|
|
1223
|
+
const { substantive, toolCalls, userChars, assistantChars, memorySignal, skillSignal } = state.turn;
|
|
1224
|
+
return {
|
|
1225
|
+
substantive,
|
|
1226
|
+
toolCalls,
|
|
1227
|
+
userChars,
|
|
1228
|
+
assistantChars,
|
|
1229
|
+
memorySignal,
|
|
1230
|
+
skillSignal
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* The evidence index of one session, or undefined when the log cannot be classified.
|
|
1235
|
+
*
|
|
1236
|
+
* undefined covers both the missing unit and a log whose frames carry no seq: the plan path's
|
|
1237
|
+
* EVIDENCE_CLASS row is report-only and must stay silent rather than report every op.
|
|
1238
|
+
* @param ctx - a context of the runtime.
|
|
1239
|
+
* @param session - the session the review plan is authored against.
|
|
1240
|
+
* @returns an index answering "does this seq carry content?".
|
|
1241
|
+
*/
|
|
1242
|
+
function sessionEvidenceIndex(ctx, session) {
|
|
1243
|
+
if (!isProjectableSession(session)) return void 0;
|
|
1244
|
+
const state = projectionService(ctx)?.evidence(session);
|
|
1245
|
+
if (state === void 0 || state.sequenced === 0) return void 0;
|
|
1246
|
+
const { through, bookkeeping } = state;
|
|
1247
|
+
return { has: (seq) => Number.isInteger(seq) && seq >= 0 && seq <= through && !bookkeeping.includes(seq) };
|
|
1248
|
+
}
|
|
1249
|
+
//#endregion
|
|
1250
|
+
export { countDispatches as A, supportFileReadFromPath as B, PTC_DISPATCH_EVENT as C, assertDispatchPayload as D, ToolDispatchPayloadError as E, isProgramToolName as F, KEEP_LINE_RE as G, CITATION_SUPPORT_DIRS as H, isSkillReadToolName as I, scanBodyHooks as J, isFileShapedPath as K, isSkillToolName as L, dispatchPathOf as M, dispatchStepOf as N, collectReadSkillNames as O, foldToolDispatches as P, readDispatchSignal as R, NATIVE_RESULT_EVENT as S, ToolDispatchNormalizer as T, DEFAULT_CITATION_REF_BUDGET as U, supportFileReadOf as V, HOOK_LINE_RE as W, observeEvent as _, evolutionSignalsProjection as a, MODEL_SESSION_EVENT_TYPES as b, sessionLastEventTime as c, evidenceKindIndex as d, isBookkeepingFrame as f, initialTurnFold as g, foldTurnEvents as h, evolutionReadsProjection as i, dispatchKeyOf as j, collectReadSupportFiles as k, sessionReadNames as l, foldTurnEvent as m, evolutionEvidenceProjection as n, isProjectableSession as o, advanceReview as p, resolveCitations as q, evolutionProjectionHistoryProjection as r, sessionEvidenceIndex as s, evolutionActivityProjection as t, sessionTurnSignals as u, DEFAULT_SUPPORT_READ_TOOL_NAMES as v, PTC_DISPATCH_START_EVENT as w, NATIVE_CALL_EVENT as x, DISPATCH_EVENT_TYPES as y, skillReadNameOf as z };
|