@multileaf/ai-workflow 0.6.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +9 -1
- package/dist/context-benchmark.d.ts +52 -0
- package/dist/context-benchmark.js +170 -0
- package/dist/cost-attribution.d.ts +65 -0
- package/dist/cost-attribution.js +119 -0
- package/dist/human-approval.d.ts +4 -0
- package/dist/human-approval.js +22 -2
- package/dist/interpreter.d.ts +8 -1
- package/dist/interpreter.js +8 -1
- package/dist/model-routing.d.ts +38 -0
- package/dist/model-routing.js +116 -0
- package/dist/recommendations.js +13 -0
- package/dist/task-parity.d.ts +67 -0
- package/dist/task-parity.js +202 -0
- package/dist/token-usage.d.ts +6 -0
- package/dist/token-usage.js +32 -5
- package/dist/traceability.d.ts +2 -0
- package/dist/traceability.js +35 -0
- package/dist/usage-sidecar.d.ts +56 -0
- package/dist/usage-sidecar.js +187 -0
- package/dist/workflow.js +470 -50
- package/docs/README.md +2 -0
- package/docs/telemetry.md +3 -1
- package/docs/token-efficiency-research.md +135 -0
- package/docs/token-efficiency-study-notes.md +128 -0
- package/docs/token-efficiency.md +104 -0
- package/package.json +1 -1
- package/resources/package.yaml +1 -0
- package/resources/skills/ticket.md +18 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { isSeq, parseDocument } from "yaml";
|
|
2
|
+
/**
|
|
3
|
+
* Usage sidecar (switchboard pattern): per-run token records with billing
|
|
4
|
+
* tiers, measurement labels, and harness attribution, stored alongside
|
|
5
|
+
* workflow checkpoints.
|
|
6
|
+
*
|
|
7
|
+
* Honest-measurement rules (docs/token-efficiency-study-notes.md):
|
|
8
|
+
* - every entry carries `measured` or `estimated`; aggregates propagate the
|
|
9
|
+
* label pessimistically (any estimated component makes the total estimated);
|
|
10
|
+
* - no timestamps: entries are ordered by a monotonic sequence number, so
|
|
11
|
+
* unchanged input produces byte-identical output;
|
|
12
|
+
* - naive `tokens x price` accounting overstates savings on cache-heavy
|
|
13
|
+
* agents, so tiers are kept separate and cache hit rate is a first-class
|
|
14
|
+
* metric. Cost conversion is deliberately not built in: provider prices
|
|
15
|
+
* rot, and unlabeled dollars would be dishonest by default.
|
|
16
|
+
*/
|
|
17
|
+
export const USAGE_SIDECAR_SCHEMA = 1;
|
|
18
|
+
export const USAGE_SIDECAR_PATH = "checkpoints/usage-sidecar.yml";
|
|
19
|
+
export const USAGE_SIDECAR_CAP = 500;
|
|
20
|
+
export const USAGE_TIERS = ["cache-read", "fresh-input", "cache-write", "output"];
|
|
21
|
+
export function validateUsageSidecarEntry(entry) {
|
|
22
|
+
if (!Number.isInteger(entry.seq) || entry.seq < 1)
|
|
23
|
+
throw new Error("Usage sidecar seq must be a positive integer.");
|
|
24
|
+
if (!entry.command.trim())
|
|
25
|
+
throw new Error("Usage sidecar command must not be empty.");
|
|
26
|
+
for (const tier of USAGE_TIERS) {
|
|
27
|
+
const value = entry.tiers[tier];
|
|
28
|
+
if (!Number.isInteger(value) || value < 0)
|
|
29
|
+
throw new Error(`Usage sidecar tier ${tier} must be a non-negative integer.`);
|
|
30
|
+
}
|
|
31
|
+
if (!USAGE_TIERS.some((tier) => entry.tiers[tier] > 0))
|
|
32
|
+
throw new Error("Usage sidecar entry needs at least one non-zero tier.");
|
|
33
|
+
if (entry.model !== undefined && !entry.model.trim())
|
|
34
|
+
throw new Error("Usage sidecar model must be a non-empty string when present.");
|
|
35
|
+
if (entry.requirement !== undefined && !/^REQ-\d+$/.test(entry.requirement))
|
|
36
|
+
throw new Error("Usage sidecar requirement must use the REQ-### identifier format.");
|
|
37
|
+
if (entry.workflow !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(entry.workflow))
|
|
38
|
+
throw new Error("Usage sidecar workflow must be a workflow id or ticket identifier without spaces.");
|
|
39
|
+
for (const [name, value] of [
|
|
40
|
+
["harness", entry.harness],
|
|
41
|
+
["harnessVersion", entry.harnessVersion],
|
|
42
|
+
])
|
|
43
|
+
if (value !== undefined && !value.trim())
|
|
44
|
+
throw new Error(`Usage sidecar ${name} must be a non-empty string when present.`);
|
|
45
|
+
return entry;
|
|
46
|
+
}
|
|
47
|
+
export function parseUsageSidecar(content) {
|
|
48
|
+
if (!content.trim())
|
|
49
|
+
return [];
|
|
50
|
+
const document = parseDocument(content);
|
|
51
|
+
if (document.errors.length)
|
|
52
|
+
throw new Error("Usage sidecar is not valid YAML.");
|
|
53
|
+
const node = document.get("entries");
|
|
54
|
+
if (node === null || node === undefined)
|
|
55
|
+
throw new Error("Usage sidecar is missing entries.");
|
|
56
|
+
if (!isSeq(node))
|
|
57
|
+
throw new Error("Usage sidecar entries must be a list.");
|
|
58
|
+
const schema = document.get("schema");
|
|
59
|
+
if (schema !== USAGE_SIDECAR_SCHEMA)
|
|
60
|
+
throw new Error(`Usage sidecar schema must be version ${USAGE_SIDECAR_SCHEMA}.`);
|
|
61
|
+
const entries = node.items.map((raw) => {
|
|
62
|
+
const pick = (key) => typeof raw.get === "function"
|
|
63
|
+
? raw.get(key)
|
|
64
|
+
: raw[key];
|
|
65
|
+
const tiers = {};
|
|
66
|
+
const rawTiers = pick("tiers");
|
|
67
|
+
if (rawTiers === null || typeof rawTiers !== "object")
|
|
68
|
+
throw new Error("Usage sidecar entry is missing tiers.");
|
|
69
|
+
const readTier = (tier) => typeof rawTiers.get === "function"
|
|
70
|
+
? rawTiers.get(tier)
|
|
71
|
+
: rawTiers[tier];
|
|
72
|
+
for (const tier of USAGE_TIERS) {
|
|
73
|
+
const value = readTier(tier);
|
|
74
|
+
if (value !== null && value !== undefined)
|
|
75
|
+
tiers[tier] = value;
|
|
76
|
+
}
|
|
77
|
+
const optional = (key) => {
|
|
78
|
+
const value = pick(key);
|
|
79
|
+
return value === null || value === undefined ? undefined : String(value);
|
|
80
|
+
};
|
|
81
|
+
return validateUsageSidecarEntry({
|
|
82
|
+
seq: pick("seq"),
|
|
83
|
+
command: String(pick("command")),
|
|
84
|
+
label: pick("label"),
|
|
85
|
+
tiers: Object.fromEntries(USAGE_TIERS.map((tier) => [tier, tiers[tier] ?? 0])),
|
|
86
|
+
...(optional("model") === undefined ? {} : { model: optional("model") }),
|
|
87
|
+
...(optional("harness") === undefined ? {} : { harness: optional("harness") }),
|
|
88
|
+
...(optional("harness_version") === undefined
|
|
89
|
+
? {}
|
|
90
|
+
: { harnessVersion: optional("harness_version") }),
|
|
91
|
+
...(optional("requirement") === undefined ? {} : { requirement: optional("requirement") }),
|
|
92
|
+
...(optional("workflow") === undefined ? {} : { workflow: optional("workflow") }),
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
const sequences = entries.map((entry) => entry.seq);
|
|
96
|
+
if (new Set(sequences).size !== sequences.length)
|
|
97
|
+
throw new Error("Usage sidecar sequence numbers must be unique.");
|
|
98
|
+
return entries;
|
|
99
|
+
}
|
|
100
|
+
export function serializeUsageSidecar(entries) {
|
|
101
|
+
const lines = [`schema: ${USAGE_SIDECAR_SCHEMA}`, "entries:"];
|
|
102
|
+
for (const entry of entries) {
|
|
103
|
+
lines.push(` - seq: ${entry.seq}`, ` command: ${entry.command}`, ` label: ${entry.label}`, " tiers:", ...USAGE_TIERS.map((tier) => ` ${tier}: ${entry.tiers[tier]}`), ...(entry.model === undefined ? [] : [` model: ${entry.model}`]), ...(entry.harness === undefined ? [] : [` harness: ${entry.harness}`]), ...(entry.harnessVersion === undefined
|
|
104
|
+
? []
|
|
105
|
+
: [` harness_version: ${entry.harnessVersion}`]), ...(entry.requirement === undefined ? [] : [` requirement: ${entry.requirement}`]), ...(entry.workflow === undefined ? [] : [` workflow: ${entry.workflow}`]));
|
|
106
|
+
}
|
|
107
|
+
return lines.join("\n") + "\n";
|
|
108
|
+
}
|
|
109
|
+
/** Append an entry, assigning the next sequence number. Drops nothing: the ledger is capped by the caller. */
|
|
110
|
+
export function appendUsageSidecarEntry(entries, entry) {
|
|
111
|
+
validateUsageSidecarEntry({ ...entry, seq: 1 });
|
|
112
|
+
const nextSeq = entries.reduce((max, existing) => Math.max(max, existing.seq), 0) + 1;
|
|
113
|
+
const recorded = [...entries, { ...entry, seq: nextSeq }];
|
|
114
|
+
return recorded.length > USAGE_SIDECAR_CAP
|
|
115
|
+
? recorded.slice(recorded.length - USAGE_SIDECAR_CAP)
|
|
116
|
+
: recorded;
|
|
117
|
+
}
|
|
118
|
+
const totalTokens = (entry) => USAGE_TIERS.reduce((total, tier) => total + entry.tiers[tier], 0);
|
|
119
|
+
export function summarizeUsageSidecar(entries) {
|
|
120
|
+
if (!entries.length)
|
|
121
|
+
return {
|
|
122
|
+
entries: 0,
|
|
123
|
+
label: "measured",
|
|
124
|
+
tiers: Object.fromEntries(USAGE_TIERS.map((tier) => [tier, 0])),
|
|
125
|
+
cacheHitRate: undefined,
|
|
126
|
+
byModel: [],
|
|
127
|
+
byHarness: [],
|
|
128
|
+
};
|
|
129
|
+
const tiers = Object.fromEntries(USAGE_TIERS.map((tier) => [
|
|
130
|
+
tier,
|
|
131
|
+
entries.reduce((total, entry) => total + entry.tiers[tier], 0),
|
|
132
|
+
]));
|
|
133
|
+
const billableInput = tiers["cache-read"] + tiers["fresh-input"];
|
|
134
|
+
const group = (key) => {
|
|
135
|
+
const map = new Map();
|
|
136
|
+
for (const entry of entries) {
|
|
137
|
+
const name = entry[key] ?? "unattributed";
|
|
138
|
+
const bucket = map.get(name) ?? { tokens: 0, measured: true };
|
|
139
|
+
bucket.tokens += totalTokens(entry);
|
|
140
|
+
bucket.measured = bucket.measured && entry.label === "measured";
|
|
141
|
+
map.set(name, bucket);
|
|
142
|
+
}
|
|
143
|
+
return [...map]
|
|
144
|
+
.map(([name, { tokens, measured }]) => ({
|
|
145
|
+
name,
|
|
146
|
+
tokens,
|
|
147
|
+
label: measured ? "measured" : "estimated",
|
|
148
|
+
}))
|
|
149
|
+
.sort((a, b) => b.tokens - a.tokens || a.name.localeCompare(b.name));
|
|
150
|
+
};
|
|
151
|
+
return {
|
|
152
|
+
entries: entries.length,
|
|
153
|
+
label: entries.every((entry) => entry.label === "measured") ? "measured" : "estimated",
|
|
154
|
+
tiers,
|
|
155
|
+
...(billableInput > 0 ? { cacheHitRate: tiers["cache-read"] / billableInput } : {}),
|
|
156
|
+
byModel: group("model").map(({ name, tokens, label }) => ({ model: name, tokens, label })),
|
|
157
|
+
byHarness: group("harness").map(({ name, tokens, label }) => ({
|
|
158
|
+
harness: name,
|
|
159
|
+
tokens,
|
|
160
|
+
label,
|
|
161
|
+
})),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
export function serializeUsageSidecarSummary(summary) {
|
|
165
|
+
if (!summary.entries)
|
|
166
|
+
return "No usage sidecar entries recorded.";
|
|
167
|
+
const percent = summary.cacheHitRate === undefined ? undefined : `${Math.round(summary.cacheHitRate * 100)}%`;
|
|
168
|
+
return [
|
|
169
|
+
`entries: ${summary.entries} (label: ${summary.label})`,
|
|
170
|
+
...USAGE_TIERS.map((tier) => ` ${tier}: ${summary.tiers[tier].toLocaleString("en-US")} tokens`),
|
|
171
|
+
...(percent === undefined
|
|
172
|
+
? []
|
|
173
|
+
: [` cache_hit_rate: ${percent} (cache-read / billable input)`]),
|
|
174
|
+
...(summary.byModel.length
|
|
175
|
+
? [
|
|
176
|
+
"by model:",
|
|
177
|
+
...summary.byModel.map(({ model, tokens, label }) => ` - ${model}: ${tokens.toLocaleString("en-US")} (${label})`),
|
|
178
|
+
]
|
|
179
|
+
: []),
|
|
180
|
+
...(summary.byHarness.length
|
|
181
|
+
? [
|
|
182
|
+
"by harness:",
|
|
183
|
+
...summary.byHarness.map(({ harness, tokens, label }) => ` - ${harness}: ${tokens.toLocaleString("en-US")} (${label})`),
|
|
184
|
+
]
|
|
185
|
+
: []),
|
|
186
|
+
].join("\n");
|
|
187
|
+
}
|