skillar 0.2.1 → 0.3.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.
Files changed (111) hide show
  1. package/NOTICE +280 -0
  2. package/README.md +37 -5
  3. package/dist/analysis/finding.js +8 -190
  4. package/dist/analysis/kernel.js +896 -0
  5. package/dist/analysis/tree.js +7 -154
  6. package/dist/analysis/usage.js +9 -394
  7. package/dist/api/flows.js +42 -212
  8. package/dist/api/report-kernel.js +1063 -0
  9. package/dist/api/routes.js +12 -2
  10. package/dist/catalog/fields.js +138 -146
  11. package/dist/catalog/watcher.js +7 -2
  12. package/dist/cli/init.js +45 -0
  13. package/dist/cli/main.js +76 -3
  14. package/dist/cli/private-skills.js +122 -0
  15. package/dist/cli/serve.js +15 -1
  16. package/dist/cli/sync.js +124 -0
  17. package/dist/dashboard/NOTICE +280 -0
  18. package/dist/dashboard/assets/app.js +737 -275
  19. package/dist/dashboard/assets/astryx-reset.css +407 -0
  20. package/dist/dashboard/assets/astryx.css +1077 -0
  21. package/dist/dashboard/assets/charts.css +54 -0
  22. package/dist/dashboard/assets/chunk-TPGDA2J4.js +1 -0
  23. package/dist/dashboard/assets/chunk-YLWHVDMP.js +36 -0
  24. package/dist/dashboard/assets/controls.css +207 -0
  25. package/dist/dashboard/assets/overlays.css +132 -0
  26. package/dist/dashboard/assets/p1.css +135 -0
  27. package/dist/dashboard/assets/shell.css +71 -0
  28. package/dist/dashboard/assets/skillar-theme.css +692 -0
  29. package/dist/dashboard/assets/styles.css +224 -121
  30. package/dist/dashboard/assets/tokens.css +278 -0
  31. package/dist/dashboard/assets/widgets.css +83 -0
  32. package/dist/dashboard/index.html +11 -2
  33. package/dist/dashboard/viewers/viewers.css +61 -0
  34. package/dist/ingest/attribution.js +5 -1
  35. package/dist/ingest/pipeline.js +2 -0
  36. package/dist/ingest/request-recorder.js +39 -0
  37. package/dist/mcp/dispatch.js +2 -2
  38. package/dist/mcp/http.js +43 -3
  39. package/dist/mcp/skills-extension.js +42 -15
  40. package/dist/mcp/stdio-proxy.js +24 -3
  41. package/dist/mcp/tools.js +38 -24
  42. package/dist/packs/claude-code.js +22 -11
  43. package/dist/packs/cursor.js +9 -4
  44. package/dist/packs/gemini.js +9 -4
  45. package/dist/packs/json-config.js +41 -0
  46. package/dist/packs/omo.js +15 -6
  47. package/dist/request-status.js +81 -0
  48. package/dist/search/fts.js +93 -58
  49. package/dist/search/fusion.js +49 -47
  50. package/dist/search/guidance.js +18 -6
  51. package/dist/search/index.js +291 -70
  52. package/dist/search/lexical.js +71 -63
  53. package/dist/server.js +12 -0
  54. package/dist/skills/apply.js +130 -0
  55. package/dist/skills/capture.js +54 -0
  56. package/dist/skills/cloud-plan.js +57 -0
  57. package/dist/skills/cloud.js +81 -0
  58. package/dist/skills/fs.js +133 -0
  59. package/dist/skills/package.js +734 -0
  60. package/dist/skills/plan.js +83 -0
  61. package/dist/skills/receipt.js +44 -0
  62. package/dist/skills/rollback.js +119 -0
  63. package/dist/skills/transfer.js +51 -0
  64. package/dist/store/db.js +7 -1
  65. package/dist/store/execution.js +2 -34
  66. package/dist/store/export.js +25 -4
  67. package/dist/store/migrations/007_sync.sql +49 -0
  68. package/dist/store/migrations/008_connector_commands.sql +12 -0
  69. package/dist/store/queries.js +33 -7
  70. package/dist/store/writes.js +38 -5
  71. package/dist/sync/cloud-blobs.js +175 -0
  72. package/dist/sync/cloud-commands.js +101 -0
  73. package/dist/sync/cloud-connection.js +105 -0
  74. package/dist/sync/cloud-delivery.js +114 -0
  75. package/dist/sync/cloud-documents.js +103 -0
  76. package/dist/sync/cloud-export.js +67 -0
  77. package/dist/sync/cloud-http.js +150 -0
  78. package/dist/sync/cloud-jobs.js +94 -0
  79. package/dist/sync/cloud-pending.js +143 -0
  80. package/dist/sync/cloud-prepare.js +101 -0
  81. package/dist/sync/cloud-restore.js +136 -0
  82. package/dist/sync/cloud-rollback.js +24 -0
  83. package/dist/sync/cloud-runner.js +86 -0
  84. package/dist/sync/cloud-runtime.js +293 -0
  85. package/dist/sync/cloud-schema.js +32 -0
  86. package/dist/sync/cloud-stage.js +112 -0
  87. package/dist/sync/cloud-wire.js +693 -0
  88. package/dist/sync/cloud-worker.js +57 -0
  89. package/dist/sync/cloud.js +157 -0
  90. package/dist/sync/command-apply.js +140 -0
  91. package/dist/sync/command-control.js +25 -0
  92. package/dist/sync/command-wire.js +437 -0
  93. package/dist/sync/consent.js +130 -0
  94. package/dist/sync/journal.js +43 -0
  95. package/dist/sync/outbox.js +134 -0
  96. package/dist/sync/restore-rows.js +125 -0
  97. package/dist/sync/restore.js +174 -0
  98. package/dist/sync/snapshot.js +78 -0
  99. package/dist/sync/spool-request.js +103 -0
  100. package/dist/sync/tables.js +27 -0
  101. package/dist/sync/triggers.js +34 -0
  102. package/dist/workflow/compare.js +3 -43
  103. package/docs/cloud-sync.md +94 -0
  104. package/docs/private-skills.md +75 -0
  105. package/docs/sync-p4.md +102 -0
  106. package/docs/sync-restore.md +167 -0
  107. package/package.json +18 -5
  108. package/src/store/migrations/007_sync.sql +49 -0
  109. package/src/store/migrations/008_connector_commands.sql +12 -0
  110. package/dist/dashboard/assets/chunk-5DFWNJC2.js +0 -1
  111. package/dist/dashboard/assets/chunk-S6B2HJQA.js +0 -17
@@ -1,157 +1,10 @@
1
- import { scopeSession } from "../store/execution.js";
2
- const PROMPT_JOIN_WINDOW_MS = 5_000;
1
+ import * as kernel from "./kernel.js";
2
+ // The analysis runs in the shared MIT kernel; these annotations keep the local signatures and check that the
3
+ // local store and tree types still match the portable contract.
3
4
  /** Pure assembly: prompt pairs precede keyless timestamp membership; row order breaks equal-time event ties.
4
5
  * A boundary at the same timestamp wins over the preceding turn, independent of ingest order.
5
6
  */
6
- export function assembleSession(data) {
7
- // These are local accumulators, never cached or written back to the store.
8
- const boundaries = new Map();
9
- const add = (id, startedAt, basis) => {
10
- const old = boundaries.get(id);
11
- if (!old || startedAt < old.startedAt)
12
- boundaries.set(id, { id, startedAt, basis });
13
- };
14
- if (data.runtime === "codex") {
15
- for (const span of data.spans) {
16
- if (span.name === "codex.turn_input" && span.turnKey !== undefined && span.startMs !== undefined) {
17
- add(span.turnKey, span.startMs, "reported");
18
- }
19
- }
20
- }
21
- const prompts = data.events.filter((e) => e.kind === "prompt");
22
- // Collect every reported boundary before considering fallbacks, including telemetry received after a hook.
23
- for (const prompt of prompts) {
24
- if (prompt.turnKey !== null && !boundaries.has(prompt.turnKey))
25
- add(prompt.turnKey, prompt.ts, "reported");
26
- }
27
- const reportedBoundaries = [...boundaries.values()].sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
28
- const pairedPrompts = new Map();
29
- if (data.runtime === "claude-code" || data.runtime === "codex") {
30
- for (const boundary of reportedBoundaries) {
31
- const reference = prompts.find((p) => p.turnKey === boundary.id);
32
- const strength = (prompt) => {
33
- if (!reference)
34
- return 0; // Codex turn_input spans carry identity and time, not prompt content.
35
- if (reference.text !== null && prompt.text !== null && reference.text !== prompt.text)
36
- return -1;
37
- const length = reference.textLength ?? reference.data.promptLength;
38
- const observedLength = prompt.textLength ?? prompt.data.promptLength;
39
- if (typeof length === "number" && typeof observedLength === "number" && length !== observedLength)
40
- return -1;
41
- if (reference.text !== null && prompt.text !== null)
42
- return 2;
43
- return typeof length === "number" && length === observedLength ? 1 : 0;
44
- };
45
- // Each boundary consumes one observation, and each observation can be consumed only once.
46
- // Exclude contradictory capture; prefer captured identity, then nearest time, with earlier ties.
47
- const match = prompts.filter((p) => p.turnKey === null && !pairedPrompts.has(p.id) &&
48
- Math.abs(boundary.startedAt - p.ts) <= PROMPT_JOIN_WINDOW_MS && strength(p) >= 0)
49
- .sort((a, b) => strength(b) - strength(a) ||
50
- Math.abs(boundary.startedAt - a.ts) - Math.abs(boundary.startedAt - b.ts) ||
51
- a.ts - b.ts || a.id.localeCompare(b.id))[0];
52
- if (match)
53
- pairedPrompts.set(match.id, boundary.id);
54
- }
55
- }
56
- for (const prompt of prompts) {
57
- if (prompt.turnKey === null && !pairedPrompts.has(prompt.id)) {
58
- add(`prompt:${prompt.id}`, prompt.ts, "inferred_time");
59
- }
60
- }
61
- const ordered = [...boundaries.values()].sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id));
62
- const newestFirst = [...ordered].reverse();
63
- const byTurn = new Map();
64
- const unassignedEvents = [];
65
- for (const event of data.events) {
66
- let key = event.turnKey ?? pairedPrompts.get(event.id) ?? null;
67
- let basis = "reported";
68
- if (key === null && event.kind === "tool_call") {
69
- const joined = data.spans.filter((s) => s.turnKey !== undefined &&
70
- ((event.callId !== null && s.callId === event.callId) ||
71
- (event.spanId !== null && s.spanId === event.spanId && s.traceId === event.data.otelTraceId)));
72
- const keys = new Set(joined.map((s) => s.turnKey));
73
- if (keys.size === 1)
74
- key = joined[0]?.turnKey ?? null;
75
- basis = "span_join";
76
- }
77
- if (key === null) {
78
- key = newestFirst.find((b) => b.startedAt <= event.ts)?.id ?? null;
79
- basis = "inferred_time";
80
- }
81
- // A reported key without a known boundary is not silently relabelled as a different turn.
82
- if (key === null || !boundaries.has(key)) {
83
- unassignedEvents.push(event);
84
- continue;
85
- }
86
- const list = byTurn.get(key) ?? [];
87
- list.push({ event, basis });
88
- byTurn.set(key, list);
89
- }
90
- const lastTs = data.events.at(-1)?.ts ?? data.startedAt;
91
- const turns = ordered.map((boundary, i) => {
92
- const endedAt = ordered[i + 1]?.startedAt ?? data.endedAt ?? lastTs;
93
- const events = [];
94
- const active = new Map();
95
- for (const { event, basis } of byTurn.get(boundary.id) ?? []) {
96
- const name = typeof event.data.name === "string" ? event.data.name : "";
97
- const uri = event.skillUri ?? (typeof event.data.uri === "string" ? event.data.uri : null);
98
- if (event.kind === "load" || event.kind === "native_skill") {
99
- const skillName = name || uri?.split("/").at(-2) || "unknown";
100
- const skill = uri ?? skillName;
101
- // Native and MCP observations of the same named skill are one activation, not two co-active skills.
102
- const existing = [...active.values()].find((s) => s.skill === skill || (s.name === skillName && (s.uri === null || uri === null)));
103
- if (!existing) {
104
- const activation = { ...event, basis, attribution: "no_skill", skills: [] };
105
- active.set(skill, { id: event.id, skill, uri, name: skillName, startedAt: event.ts, endedAt, activation, events: [] });
106
- }
107
- else if (existing.uri === null && uri !== null) {
108
- existing.uri = uri;
109
- }
110
- }
111
- const reported = event.kind === "llm_call" && typeof event.data.skillName === "string" ? event.data.skillName : null;
112
- const action = event.kind === "tool_call" || event.kind === "llm_call";
113
- const skills = reported !== null ? [reported] : action ? [...active.keys()] : [];
114
- const assigned = { ...event, basis, skills,
115
- attribution: reported !== null ? "reported" : skills.length > 1 ? "co_active" : skills.length === 1 ? "single" : "no_skill" };
116
- events.push(assigned);
117
- if (action) {
118
- for (const span of active.values()) {
119
- if (reported === null || span.name === reported || span.skill === reported)
120
- span.events.push(assigned);
121
- }
122
- }
123
- }
124
- const skillSpans = [...active.values()];
125
- return { ...boundary, endedAt, events, skillSpans };
126
- });
127
- return { id: data.id, runtime: data.runtime, startedAt: data.startedAt, endedAt: data.endedAt, turns, unassignedEvents };
128
- }
129
- export function sessionTree(store, sessionId) {
130
- const data = store.treeSessionData(sessionId);
131
- return data ? assembleSession(data) : undefined;
132
- }
133
- export function flowTree(store, flowOrWorkspaceId, scope = store.flowEventScope(flowOrWorkspaceId)) {
134
- const data = store.treeFlowData(flowOrWorkspaceId, scope);
135
- if (!data)
136
- return undefined;
137
- const sessions = new Map();
138
- for (const link of data.links) {
139
- if (link.sessionId !== null && !sessions.has(link.sessionId)) {
140
- const input = store.treeSessionData(link.sessionId, scope);
141
- const session = input ? assembleSession(input) : null;
142
- sessions.set(link.sessionId, session && scope ? scopeSession(session, scope) : session);
143
- }
144
- }
145
- return { id: data.id, workspaceId: data.workspaceId, label: data.label, registered: data.registered,
146
- tabs: data.tabs.map((tab) => ({ ...tab, panes: data.panes.filter((p) => p.tabId === tab.id).map((pane) => ({
147
- ...pane, sessions: data.links.filter((l) => l.paneId === pane.id).map((link) => ({ ...link,
148
- basis: link.source === "inferred:cwd_time" ? "inferred" : "reported",
149
- session: link.sessionId === null ? null : sessions.get(link.sessionId) ?? null })),
150
- })) })) };
151
- }
152
- export function outsideHerdr(store, opts) {
153
- return { id: "outside-herdr", sessions: store.outsideHerdrSessionIds(opts).flatMap((id) => {
154
- const session = sessionTree(store, id);
155
- return session ? [session] : [];
156
- }) };
157
- }
7
+ export const assembleSession = kernel.assembleSession;
8
+ export const sessionTree = kernel.sessionTree;
9
+ export const flowTree = kernel.flowTree;
10
+ export const outsideHerdr = kernel.outsideHerdr;
@@ -1,394 +1,9 @@
1
- import { isSkillarMcpData } from "../ingest/identity.js";
2
- import { flowTree, sessionTree } from "./tree.js";
3
- /** "Used the skill?" per skill span, computed on read from reported events only; an unknown is `null`, never 0. */
4
- /** The measurements a model call can report. A runtime that omits one measured nothing, which is never a zero. */
5
- export const TOKEN_KEYS = ["inputTokens", "outputTokens", "cacheReadTokens", "cacheCreationTokens", "cacheWriteTokens",
6
- "reasoningTokens", "totalTokens"];
7
- const KOREAN_CORRECTIONS = ["아니", "다시", "틀렸", "잘못", "그게 아니", "왜 안"];
8
- const ENGLISH_CORRECTIONS = ["no,", "wrong", "again", "that's not", "undo", "revert"];
9
- function escapeRegex(text) {
10
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11
- }
12
- /** "again" must not fire inside "against"; "no," carries its own right-hand boundary. */
13
- const ENGLISH_PATTERNS = ENGLISH_CORRECTIONS.map((token) => [
14
- token,
15
- new RegExp(`${/^[a-z0-9]/.test(token) ? "(?<![a-z0-9])" : ""}${escapeRegex(token)}${/[a-z0-9]$/.test(token) ? "(?![a-z0-9])" : ""}`, "i"),
16
- ]);
17
- function numberOf(value) {
18
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
19
- }
20
- function stringOf(value) {
21
- return typeof value === "string" && value.length > 0 ? value : undefined;
22
- }
23
- /** Case-insensitive word-list match; typographic apostrophes are folded so "that’s not" reads as "that's not". */
24
- export function correctionMatches(text) {
25
- const normalized = text.replace(/[\u2018\u2019]/g, "'").toLowerCase();
26
- const matched = [];
27
- for (const token of KOREAN_CORRECTIONS)
28
- if (normalized.includes(token))
29
- matched.push(token);
30
- for (const [token, pattern] of ENGLISH_PATTERNS)
31
- if (pattern.test(normalized))
32
- matched.push(token);
33
- return matched;
34
- }
35
- function correctionOf(next) {
36
- if (next === null)
37
- return { status: "unknown", label: "heuristic", matched: [], reason: "no_next_prompt" };
38
- // Capture level metadata (and a runtime that reports no prompt text) leaves nothing to match on.
39
- if (next.text === null)
40
- return { status: "unknown", label: "heuristic", matched: [], reason: "text_not_captured" };
41
- const matched = correctionMatches(next.text);
42
- return { status: matched.length > 0 ? "correction" : "no_correction", label: "heuristic", matched, reason: null };
43
- }
44
- /** The first prompt of a later turn in the same session; turns without a prompt event (Codex spans) are skipped. */
45
- export function nextPromptAfterTurn(session, turnIndex) {
46
- for (let i = turnIndex + 1; i < session.turns.length; i += 1) {
47
- const prompt = session.turns[i]?.events.find((e) => e.kind === "prompt");
48
- if (prompt)
49
- return prompt;
50
- }
51
- return null;
52
- }
53
- function callTokens(data) {
54
- const measured = {};
55
- const unknownCalls = {};
56
- for (const key of TOKEN_KEYS) {
57
- const value = numberOf(data[key]);
58
- measured[key] = value ?? null;
59
- unknownCalls[key] = value === undefined ? 1 : 0;
60
- }
61
- return { inputIncludesCache: data.inputIncludesCache === true, calls: 1, ...measured, unknownCalls };
62
- }
63
- /** An unreported measurement adds nothing: the sum covers the calls that reported it, unknownCalls counts the rest. */
64
- function sumTokens(a, b) {
65
- const measured = {};
66
- const unknownCalls = {};
67
- for (const key of TOKEN_KEYS) {
68
- const left = a[key];
69
- const right = b[key];
70
- measured[key] = left === null ? right : right === null ? left : left + right;
71
- unknownCalls[key] = a.unknownCalls[key] + b.unknownCalls[key];
72
- }
73
- return { inputIncludesCache: a.inputIncludesCache, calls: a.calls + b.calls, ...measured, unknownCalls };
74
- }
75
- function mergeTokens(into, buckets) {
76
- for (const bucket of buckets) {
77
- const current = into.get(bucket.inputIncludesCache);
78
- into.set(bucket.inputIncludesCache, current ? sumTokens(current, bucket) : bucket);
79
- }
80
- }
81
- function sortedTokens(buckets) {
82
- return [...buckets.values()].sort((a, b) => Number(a.inputIncludesCache) - Number(b.inputIncludesCache));
83
- }
84
- function skillDirHint(span) {
85
- const path = stringOf(span.activation.data.path);
86
- if (path === undefined)
87
- return null;
88
- const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
89
- return cut > 0 ? path.slice(0, cut) : null;
90
- }
91
- function readFileBelongsTo(event, span) {
92
- const skillUri = event.skillUri ?? stringOf(event.data.skillUri) ?? null;
93
- if (skillUri === null)
94
- return false;
95
- if (span.uri !== null)
96
- return skillUri === span.uri;
97
- return skillUri.split("/").at(-2) === span.name;
98
- }
99
- const COMMAND_KEYS = new Set(["command", "full_command", "bash_command", "cmd", "argv", "script", "shell_command"]);
100
- /**
101
- * The strings an argument blob can hold. A JSON value under a command key (and any text that is not JSON)
102
- * is a command line; every other JSON string is one path argument and keeps its spaces and quotes as data.
103
- */
104
- function collectArgStrings(text) {
105
- let parsed;
106
- try {
107
- parsed = JSON.parse(text);
108
- }
109
- catch {
110
- return [{ text, command: true }];
111
- }
112
- const out = [];
113
- const walk = (value, command) => {
114
- if (typeof value === "string")
115
- out.push({ text: value, command });
116
- else if (Array.isArray(value))
117
- for (const item of value)
118
- walk(item, command);
119
- else if (value !== null && typeof value === "object") {
120
- for (const [key, item] of Object.entries(value))
121
- walk(item, command || COMMAND_KEYS.has(key));
122
- }
123
- };
124
- walk(parsed, false);
125
- return out.length > 0 ? out : [{ text, command: true }];
126
- }
127
- /**
128
- * Shell-like split of a command line: whitespace separates, single and double quotes group and are dropped.
129
- * A backslash escapes a separator, a quote or itself; anywhere else it stays, so `C:\skills\x` survives intact.
130
- */
131
- function shellTokens(text) {
132
- const tokens = [];
133
- let current = "";
134
- let open = false;
135
- let quote = null;
136
- for (let i = 0; i < text.length; i += 1) {
137
- const char = text[i];
138
- if (quote === null && /\s/.test(char)) {
139
- if (open)
140
- tokens.push(current);
141
- current = "";
142
- open = false;
143
- continue;
144
- }
145
- if (quote === null && (char === '"' || char === "'")) {
146
- quote = char;
147
- open = true;
148
- continue;
149
- }
150
- if (quote === char) {
151
- quote = null;
152
- continue;
153
- }
154
- const next = text[i + 1];
155
- if (char === "\\" && quote !== "'" && next !== undefined && (/\s/.test(next) || next === '"' || next === "'" || next === "\\")) {
156
- current += next;
157
- open = true;
158
- i += 1;
159
- continue;
160
- }
161
- current += char;
162
- open = true;
163
- }
164
- if (open)
165
- tokens.push(current);
166
- return tokens;
167
- }
168
- function normalizePath(path) {
169
- return path.replace(/\\+/g, "/").replace(/\/+$/, "");
170
- }
171
- /**
172
- * Whole-token comparison, never a substring: `/skills/db-query` does not reference `/skills/db-query'backup`.
173
- * `insideOnly` drops the bare directory itself, which is what naming a directory on a command line is.
174
- */
175
- function tokenReferencesDir(token, dir, insideOnly) {
176
- const path = normalizePath(token);
177
- const target = normalizePath(dir);
178
- if (path === "" || target === "")
179
- return false;
180
- if (path.startsWith(`${target}/`))
181
- return true;
182
- const rooted = target.startsWith("/") || /^[A-Za-z]:\//.test(target);
183
- if (!rooted && path.includes(`/${target}/`))
184
- return true;
185
- if (insideOnly)
186
- return false;
187
- return path === target || (!rooted && path.endsWith(`/${target}`));
188
- }
189
- /**
190
- * Native skills leave no MCP trail, so a tool argument naming a file inside the skill directory is counted as a read.
191
- * The skill name stands in as a relative directory only while the activation reported no directory of its own.
192
- */
193
- function argsReferenceSkillDir(event, span, dirHint) {
194
- if (event.text === null)
195
- return false;
196
- const target = dirHint ?? span.name;
197
- for (const { text, command } of collectArgStrings(event.text)) {
198
- for (const token of command ? shellTokens(text) : [text]) {
199
- if (tokenReferencesDir(token, target, command))
200
- return true;
201
- }
202
- }
203
- return false;
204
- }
205
- function supportingReadsOf(span, turn) {
206
- const reads = [];
207
- const start = turn.events.findIndex((e) => e.id === span.activation.id);
208
- // Row order, not timestamps, decides "after the activation": events can share a millisecond.
209
- for (const event of turn.events.slice(start < 0 ? turn.events.length : start + 1)) {
210
- if (event.kind === "read_file" && readFileBelongsTo(event, span)) {
211
- reads.push({ eventId: event.id, kind: "read_file", uri: event.skillUri ?? stringOf(event.data.uri) ?? null, label: "reported" });
212
- }
213
- }
214
- if (span.activation.kind !== "native_skill")
215
- return reads;
216
- const dirHint = skillDirHint(span);
217
- for (const event of span.events) {
218
- if (event.kind !== "tool_call" || isSkillarMcpData(event.data))
219
- continue;
220
- if (argsReferenceSkillDir(event, span, dirHint)) {
221
- reads.push({ eventId: event.id, kind: "tool_call", uri: null, label: "heuristic" });
222
- }
223
- }
224
- return reads;
225
- }
226
- const SHELL_TOOLS = new Set(["exec_command", "Bash", "shell", "local_shell"]);
227
- /** Only Codex names its code-running wrapper `exec`; elsewhere the name carries no wrapper meaning. */
228
- function activityKind(event, runtime) {
229
- const toolName = stringOf(event.data.toolName);
230
- if (runtime === "codex" && toolName === "exec")
231
- return "unresolved_exec";
232
- return toolName !== undefined && SHELL_TOOLS.has(toolName) ? "command" : "other";
233
- }
234
- /** Usage of one skill span: `turn` supplies the events outside the span (MCP reads), `nextPrompt` the correction guess. */
235
- export function spanUsage(span, ctx) {
236
- let followThrough = 0;
237
- let commands = 0;
238
- let unresolvedExec = 0;
239
- const results = { success: 0, failure: 0, unknown: 0 };
240
- let skillToolCalls = 0;
241
- let toolFailures = 0;
242
- let llmCalls = 0;
243
- let costSum = 0;
244
- let costUnknownCalls = 0;
245
- let reported = 0;
246
- let single = 0;
247
- let coActive = 0;
248
- const buckets = new Map();
249
- for (const event of span.events) {
250
- if (event.attribution === "reported")
251
- reported += 1;
252
- else if (event.attribution === "co_active")
253
- coActive += 1;
254
- else if (event.attribution === "single")
255
- single += 1;
256
- if (event.kind === "tool_call") {
257
- if (isSkillarMcpData(event.data))
258
- skillToolCalls += 1;
259
- else {
260
- followThrough += 1;
261
- const kind = activityKind(event, ctx.runtime);
262
- if (kind === "command")
263
- commands += 1;
264
- else if (kind === "unresolved_exec")
265
- unresolvedExec += 1;
266
- results[event.data.success === true ? "success" : event.data.success === false ? "failure" : "unknown"] += 1;
267
- }
268
- if (event.data.success === false)
269
- toolFailures += 1;
270
- }
271
- if (event.kind === "llm_call") {
272
- llmCalls += 1;
273
- const cost = numberOf(event.data.costUsd);
274
- if (cost === undefined)
275
- costUnknownCalls += 1;
276
- else
277
- costSum += cost;
278
- mergeTokens(buckets, [callTokens(event.data)]);
279
- }
280
- }
281
- const total = span.events.length;
282
- return {
283
- turnId: ctx.turn.id, spanId: span.id, skill: span.skill, name: span.name, uri: span.uri,
284
- activatedAt: span.startedAt, durationMs: Math.max(0, span.endedAt - span.startedAt),
285
- followThrough, activity: { version: 1, observations: followThrough, commands, unresolvedExec, results,
286
- workExecutions: unresolvedExec > 0 ? null : followThrough },
287
- skillToolCalls, toolFailures, supportingReads: supportingReadsOf(span, ctx.turn), llmCalls,
288
- costUsd: llmCalls > 0 && costUnknownCalls === 0 ? costSum : null, costUnknownCalls,
289
- tokens: sortedTokens(buckets), nextPromptCorrection: correctionOf(ctx.nextPrompt),
290
- attribution: { reported, single, coActive, total, coActiveShare: total > 0 ? coActive / total : null },
291
- };
292
- }
293
- export function sessionUsage(session) {
294
- const spans = [];
295
- session.turns.forEach((turn, index) => {
296
- const nextPrompt = nextPromptAfterTurn(session, index);
297
- for (const span of turn.skillSpans)
298
- spans.push(spanUsage(span, { turn, nextPrompt, runtime: session.runtime }));
299
- });
300
- return { sessionId: session.id, runtime: session.runtime, spans };
301
- }
302
- /** Per-skill totals across any set of spans. Cost stays null while a single contributing model call reported none. */
303
- export function aggregateUsage(spans) {
304
- const bySkill = new Map();
305
- for (const usage of spans) {
306
- const acc = bySkill.get(usage.skill) ?? {
307
- skill: usage.skill, name: usage.name, uri: usage.uri, spans: 0, spansWithoutFollowThrough: 0,
308
- followThrough: 0, skillToolCalls: 0, toolFailures: 0, supportingReads: 0, heuristicReads: 0,
309
- durationMs: 0, llmCalls: 0, costSum: 0, costUnknownCalls: 0, tokens: new Map(),
310
- corrections: { correction: 0, no_correction: 0, unknown: 0 }, reported: 0, single: 0, coActive: 0, total: 0,
311
- commands: 0, unresolvedExec: 0, results: { success: 0, failure: 0, unknown: 0 }, workExecutions: 0,
312
- };
313
- acc.uri = acc.uri ?? usage.uri;
314
- acc.spans += 1;
315
- if (usage.followThrough === 0)
316
- acc.spansWithoutFollowThrough += 1;
317
- acc.followThrough += usage.followThrough;
318
- acc.skillToolCalls += usage.skillToolCalls;
319
- acc.toolFailures += usage.toolFailures;
320
- acc.supportingReads += usage.supportingReads.length;
321
- acc.heuristicReads += usage.supportingReads.filter((r) => r.label === "heuristic").length;
322
- acc.durationMs += usage.durationMs;
323
- acc.llmCalls += usage.llmCalls;
324
- acc.costSum += usage.costUsd ?? 0;
325
- acc.costUnknownCalls += usage.costUnknownCalls;
326
- mergeTokens(acc.tokens, usage.tokens);
327
- acc.corrections[usage.nextPromptCorrection.status] += 1;
328
- acc.reported += usage.attribution.reported;
329
- acc.single += usage.attribution.single;
330
- acc.coActive += usage.attribution.coActive;
331
- acc.total += usage.attribution.total;
332
- acc.commands += usage.activity.commands;
333
- acc.unresolvedExec += usage.activity.unresolvedExec;
334
- acc.results.success += usage.activity.results.success;
335
- acc.results.failure += usage.activity.results.failure;
336
- acc.results.unknown += usage.activity.results.unknown;
337
- acc.workExecutions = acc.workExecutions === null || usage.activity.workExecutions === null ? null
338
- : acc.workExecutions + usage.activity.workExecutions;
339
- bySkill.set(usage.skill, acc);
340
- }
341
- return [...bySkill.values()]
342
- .map((acc) => ({
343
- skill: acc.skill, name: acc.name, uri: acc.uri, spans: acc.spans, spansWithoutFollowThrough: acc.spansWithoutFollowThrough,
344
- followThrough: acc.followThrough, skillToolCalls: acc.skillToolCalls, toolFailures: acc.toolFailures,
345
- supportingReads: acc.supportingReads, heuristicReads: acc.heuristicReads, durationMs: acc.durationMs,
346
- llmCalls: acc.llmCalls, costUsd: acc.llmCalls > 0 && acc.costUnknownCalls === 0 ? acc.costSum : null,
347
- costUnknownCalls: acc.costUnknownCalls, tokens: sortedTokens(acc.tokens), corrections: acc.corrections,
348
- attribution: { reported: acc.reported, single: acc.single, coActive: acc.coActive, total: acc.total,
349
- coActiveShare: acc.total > 0 ? acc.coActive / acc.total : null },
350
- activity: { version: 1, observations: acc.followThrough, commands: acc.commands, unresolvedExec: acc.unresolvedExec,
351
- results: acc.results, workExecutions: acc.workExecutions },
352
- }))
353
- .sort((a, b) => a.skill.localeCompare(b.skill));
354
- }
355
- /** Usage of every session linked to one flow (or to the herdr workspace acting as one). */
356
- export function flowUsage(store, flowOrWorkspaceId) {
357
- const flow = flowTree(store, flowOrWorkspaceId);
358
- if (!flow)
359
- return undefined;
360
- const sessions = [];
361
- for (const tab of flow.tabs) {
362
- for (const pane of tab.panes) {
363
- for (const link of pane.sessions) {
364
- if (link.session === null || sessions.some((s) => s.sessionId === link.session?.id))
365
- continue;
366
- sessions.push(sessionUsage(link.session));
367
- }
368
- }
369
- }
370
- return { id: flow.id, sessions, skills: aggregateUsage(sessions.flatMap((s) => s.spans)) };
371
- }
372
- /**
373
- * Usage of the sessions in a time range. Every eligible session is analysed and aggregated; an optional
374
- * `detailLimit` shortens only the per-session list and then says so through `truncated` and `sessionCount`.
375
- */
376
- export function rangeUsage(store, opts) {
377
- const filter = { from: opts.from, to: opts.to, ...(opts.automated !== undefined ? { automated: opts.automated } : {}) };
378
- const detailLimit = opts.detailLimit === undefined ? undefined : Math.max(0, Math.floor(opts.detailLimit));
379
- const sessions = [];
380
- const spans = [];
381
- let sessionCount = 0;
382
- for (const row of store.sessions(filter)) {
383
- const tree = sessionTree(store, row.id);
384
- if (!tree)
385
- continue;
386
- const usage = sessionUsage(tree);
387
- sessionCount += 1;
388
- spans.push(...usage.spans);
389
- if (detailLimit === undefined || sessions.length < detailLimit)
390
- sessions.push(usage);
391
- }
392
- return { from: opts.from, to: opts.to, sessionCount, truncated: sessions.length < sessionCount, sessions,
393
- skills: aggregateUsage(spans) };
394
- }
1
+ import * as kernel from "./kernel.js";
2
+ export { TOKEN_KEYS } from "./kernel.js";
3
+ export const correctionMatches = kernel.correctionMatches;
4
+ export const nextPromptAfterTurn = kernel.nextPromptAfterTurn;
5
+ export const spanUsage = kernel.spanUsage;
6
+ export const sessionUsage = kernel.sessionUsage;
7
+ export const aggregateUsage = kernel.aggregateUsage;
8
+ export const flowUsage = kernel.flowUsage;
9
+ export const rangeUsage = kernel.rangeUsage;