taskflow-core 0.1.4 → 0.1.6

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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +120 -27
  3. package/dist/agents.d.ts +20 -0
  4. package/dist/agents.d.ts.map +1 -1
  5. package/dist/agents.js +51 -2
  6. package/dist/agents.js.map +1 -1
  7. package/dist/detached-runner.js +17 -0
  8. package/dist/detached-runner.js.map +1 -1
  9. package/dist/index.d.ts +7 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +7 -0
  12. package/dist/index.js.map +1 -1
  13. package/dist/interpolate.d.ts +5 -0
  14. package/dist/interpolate.d.ts.map +1 -1
  15. package/dist/interpolate.js +14 -3
  16. package/dist/interpolate.js.map +1 -1
  17. package/dist/jsonc.d.ts +30 -0
  18. package/dist/jsonc.d.ts.map +1 -0
  19. package/dist/jsonc.js +108 -0
  20. package/dist/jsonc.js.map +1 -0
  21. package/dist/library/meta.d.ts +31 -0
  22. package/dist/library/meta.d.ts.map +1 -0
  23. package/dist/library/meta.js +154 -0
  24. package/dist/library/meta.js.map +1 -0
  25. package/dist/library/search.d.ts +32 -0
  26. package/dist/library/search.d.ts.map +1 -0
  27. package/dist/library/search.js +298 -0
  28. package/dist/library/search.js.map +1 -0
  29. package/dist/library/types.d.ts +121 -0
  30. package/dist/library/types.d.ts.map +1 -0
  31. package/dist/library/types.js +18 -0
  32. package/dist/library/types.js.map +1 -0
  33. package/dist/reflexion.d.ts +46 -0
  34. package/dist/reflexion.d.ts.map +1 -0
  35. package/dist/reflexion.js +100 -0
  36. package/dist/reflexion.js.map +1 -0
  37. package/dist/runner-core.d.ts +54 -4
  38. package/dist/runner-core.d.ts.map +1 -1
  39. package/dist/runner-core.js +237 -10
  40. package/dist/runner-core.js.map +1 -1
  41. package/dist/runtime.d.ts.map +1 -1
  42. package/dist/runtime.js +353 -16
  43. package/dist/runtime.js.map +1 -1
  44. package/dist/schema.d.ts +11 -5
  45. package/dist/schema.d.ts.map +1 -1
  46. package/dist/schema.js +113 -2
  47. package/dist/schema.js.map +1 -1
  48. package/dist/scorer-runtime.d.ts +30 -0
  49. package/dist/scorer-runtime.d.ts.map +1 -0
  50. package/dist/scorer-runtime.js +134 -0
  51. package/dist/scorer-runtime.js.map +1 -0
  52. package/dist/scorers.d.ts +120 -0
  53. package/dist/scorers.d.ts.map +1 -0
  54. package/dist/scorers.js +313 -0
  55. package/dist/scorers.js.map +1 -0
  56. package/dist/store.d.ts +56 -1
  57. package/dist/store.d.ts.map +1 -1
  58. package/dist/store.js +129 -1
  59. package/dist/store.js.map +1 -1
  60. package/package.json +6 -7
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Library — search ranking (structural + keyword; Phase 1).
3
+ *
4
+ * Phase 2 adds the embedding/cosine path; the seam (LibraryDeps.embedder) is
5
+ * already in place but left unused here. When no embedder is configured OR
6
+ * structureOnly is set, search degrades to keyword + structural ranking.
7
+ *
8
+ * Refs: docs/rfc-library-reuse.md §5.2 (blend), §5.2.1 (structScore),
9
+ * §5.2.2 (staleness), §5.3 (why/reuseHint templates).
10
+ */
11
+ import { getFlow, listFlows, readMeta } from "../store.js";
12
+ import { computeGenerality, computePhaseSignature, countPhases, extractAgentUsage, } from "./meta.js";
13
+ // ---------------------------------------------------------------------------
14
+ // Levenshtein (RFC §5.2.1)
15
+ // ---------------------------------------------------------------------------
16
+ /** Standard Levenshtein edit distance (insert/delete/replace cost 1).
17
+ * O(m·n) DP; signature strings are short (<50 chars) so cost is negligible. */
18
+ export function levenshtein(a, b) {
19
+ if (a === b)
20
+ return 0;
21
+ if (a.length === 0)
22
+ return b.length;
23
+ if (b.length === 0)
24
+ return a.length;
25
+ const m = a.length;
26
+ const n = b.length;
27
+ // Two rolling rows; allocate fresh each call (signatures are tiny).
28
+ let prev = new Array(n + 1);
29
+ for (let j = 0; j <= n; j++)
30
+ prev[j] = j;
31
+ for (let i = 1; i <= m; i++) {
32
+ const curr = new Array(n + 1);
33
+ curr[0] = i;
34
+ for (let j = 1; j <= n; j++) {
35
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
36
+ curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
37
+ }
38
+ prev = curr;
39
+ }
40
+ return prev[n];
41
+ }
42
+ // ---------------------------------------------------------------------------
43
+ // Candidate resolution (RFC §5.2.2 staleness detection)
44
+ // ---------------------------------------------------------------------------
45
+ /** Resolve a saved flow + its sidecar into a candidate whose structural fields
46
+ * are ALWAYS freshly derived from the current def, and whose embedding is only
47
+ * trusted when the sidecar's phaseSignature matches the fresh one. */
48
+ export function resolveCandidate(def, scope, name, sidecar) {
49
+ const freshSig = computePhaseSignature(def);
50
+ const freshGen = computeGenerality(def);
51
+ const freshAgents = extractAgentUsage(def);
52
+ const freshCount = countPhases(def);
53
+ if (!sidecar) {
54
+ return {
55
+ name,
56
+ scope,
57
+ def,
58
+ phaseSignature: freshSig,
59
+ phaseCount: freshCount,
60
+ agentUsage: freshAgents,
61
+ generality: freshGen,
62
+ reuseCount: 0,
63
+ version: 1,
64
+ embedding: null,
65
+ embeddingStale: true,
66
+ };
67
+ }
68
+ const sigMatch = sidecar.phaseSignature === freshSig;
69
+ return {
70
+ name,
71
+ scope,
72
+ def,
73
+ phaseSignature: freshSig,
74
+ phaseCount: freshCount,
75
+ agentUsage: freshAgents,
76
+ generality: freshGen,
77
+ purpose: sidecar.purpose,
78
+ tags: sidecar.tags,
79
+ notes: sidecar.notes,
80
+ reuseCount: sidecar.reuseCount ?? 0,
81
+ version: sidecar.version ?? 1,
82
+ derivedFrom: sidecar.derivedFrom,
83
+ embedding: sigMatch ? sidecar.embedding ?? null : null,
84
+ embeddingStale: !sigMatch,
85
+ };
86
+ }
87
+ // ---------------------------------------------------------------------------
88
+ // Scoring
89
+ // ---------------------------------------------------------------------------
90
+ /** structScore ∈ [0,1]. RFC §5.2.1: 0.7*sigSim + 0.3*countPenalty. */
91
+ function computeStructScore(query, cand) {
92
+ let sigSim = 0;
93
+ if (cand.phaseSignature && query.phaseSignature) {
94
+ const d = levenshtein(query.phaseSignature, cand.phaseSignature);
95
+ const denom = Math.max(query.phaseSignature.length, cand.phaseSignature.length, 1);
96
+ sigSim = 1 - d / denom;
97
+ if (sigSim < 0)
98
+ sigSim = 0;
99
+ }
100
+ let countPenalty = 0;
101
+ if (query.phaseCount > 0 && cand.phaseCount > 0) {
102
+ const diff = Math.abs(query.phaseCount - cand.phaseCount);
103
+ countPenalty = 1 - Math.min(1, diff / Math.max(query.phaseCount, cand.phaseCount));
104
+ }
105
+ return 0.7 * sigSim + 0.3 * countPenalty;
106
+ }
107
+ /** textScore ∈ [0,1]. Token-overlap between query and the flow's text fields
108
+ * (name + purpose + tags + phase task text). CJK-aware: queries tokenized on
109
+ * whitespace AND matched as substrings, so a Chinese query token like "鉴权"
110
+ * still matches a purpose containing "...缺少鉴权检查..." (which whitespace
111
+ * alone would never split out). */
112
+ function computeTextScore(queryTokens, cand) {
113
+ if (queryTokens.length === 0)
114
+ return 0;
115
+ const fieldText = ((cand.name ?? "") +
116
+ " " +
117
+ (cand.purpose ?? "") +
118
+ " " +
119
+ (cand.tags ?? []).join(" ") +
120
+ " " +
121
+ cand.phaseTaskText).toLowerCase();
122
+ if (!fieldText.trim())
123
+ return 0;
124
+ // Substring match per query token (CJK-friendly). Longer tokens weigh more
125
+ // (they carry more signal) so e.g. a 2-char Chinese term counts more than a
126
+ // 2-char English one only marginally; this keeps the [0,1] shape intuitive.
127
+ let hits = 0;
128
+ for (const t of queryTokens) {
129
+ if (!t)
130
+ continue;
131
+ if (fieldText.includes(t))
132
+ hits++;
133
+ }
134
+ return hits / queryTokens.length;
135
+ }
136
+ function tokenize(query) {
137
+ return query
138
+ .toLowerCase()
139
+ .split(/[^\p{L}\p{N}]+/u)
140
+ .filter((t) => t.length > 1);
141
+ }
142
+ function phaseTaskText(def) {
143
+ if (!Array.isArray(def.phases))
144
+ return "";
145
+ const parts = [];
146
+ for (const p of def.phases) {
147
+ if (typeof p.task === "string")
148
+ parts.push(p.task);
149
+ if (Array.isArray(p.branches)) {
150
+ for (const b of p.branches ?? []) {
151
+ if (b?.task)
152
+ parts.push(b.task);
153
+ }
154
+ }
155
+ }
156
+ return parts.join(" ");
157
+ }
158
+ // ---------------------------------------------------------------------------
159
+ // why / reuseHint templates (RFC §5.3, Tier 1, zero-token)
160
+ // ---------------------------------------------------------------------------
161
+ function buildWhy(s) {
162
+ const hits = [];
163
+ if ((s.searchMode === "semantic" || s.searchMode === "mixed") && s.semScore != null && s.semScore > 0.7) {
164
+ hits.push(`语义命中(sem=${s.semScore.toFixed(2)})`);
165
+ }
166
+ if (s.structScore > 0.8)
167
+ hits.push(`结构一致(struct=${s.structScore.toFixed(2)})`);
168
+ if (s.textScore > 0.3)
169
+ hits.push(`关键词匹配(text=${s.textScore.toFixed(2)})`);
170
+ return hits.length > 0 ? hits.join(" + ") : "低分命中,建议检查";
171
+ }
172
+ function buildReuseHint(r) {
173
+ if (r.score >= 0.8)
174
+ return `直接复用${r.argCount > 0 ? `,注意 ${r.argCount} 个 args 参数` : ""}`;
175
+ if (r.score >= 0.5)
176
+ return `结构相似,建议 copy + 泛化后使用`;
177
+ return `低相关度,建议从头编写或大幅改写`;
178
+ }
179
+ // ---------------------------------------------------------------------------
180
+ // searchLibrary
181
+ // ---------------------------------------------------------------------------
182
+ function argCountOf(def) {
183
+ return def.args && typeof def.args === "object" ? Object.keys(def.args).length : 0;
184
+ }
185
+ /** Search the library. Returns ranked top-N. Degrades to structural/keyword
186
+ * when no embedder is configured or structureOnly is requested. */
187
+ export async function searchLibrary(deps, input) {
188
+ const limit = Math.min(20, Math.max(1, input.limit ?? 5));
189
+ const minScore = input.minScore ?? 0;
190
+ const scope = input.scope ?? deps.settings.scope ?? "both";
191
+ // gather candidates
192
+ const flows = listFlows(deps.cwd).filter((f) => {
193
+ if (scope === "both")
194
+ return true;
195
+ return f.scope === scope;
196
+ });
197
+ const queryTokens = tokenize(input.query);
198
+ // embed the query if an embedder is available and not structureOnly
199
+ let queryVec = null;
200
+ const hasEmbedder = !!deps.embedder && !input.structureOnly;
201
+ if (hasEmbedder && deps.embedder) {
202
+ try {
203
+ queryVec = await deps.embedder.embed(input.query);
204
+ }
205
+ catch {
206
+ queryVec = null; // degrade
207
+ }
208
+ }
209
+ const scored = [];
210
+ for (const f of flows) {
211
+ const sidecar = readMeta(deps.cwd, f.name);
212
+ const cand = resolveCandidate(f.def, f.scope, f.name, sidecar);
213
+ const qShape = {
214
+ phaseSignature: input.phaseSignatureHint ?? "",
215
+ phaseCount: input.phaseCountHint ?? 0,
216
+ };
217
+ const structScore = computeStructScore(qShape, cand);
218
+ const textScore = computeTextScore(queryTokens, {
219
+ name: cand.name,
220
+ purpose: cand.purpose,
221
+ tags: cand.tags,
222
+ phaseTaskText: phaseTaskText(cand.def),
223
+ });
224
+ let score;
225
+ let semScore;
226
+ const hasVectors = queryVec != null && cand.embedding != null && !cand.embeddingStale;
227
+ if (hasVectors && queryVec && cand.embedding) {
228
+ semScore = cosine(queryVec, cand.embedding);
229
+ score = 0.6 * semScore + 0.25 * structScore + 0.15 * textScore;
230
+ }
231
+ else {
232
+ score = 0.6 * textScore + 0.4 * structScore;
233
+ }
234
+ if (score < minScore)
235
+ continue;
236
+ if (score <= 0)
237
+ continue; // zero-relevance results are noise; don't surface them
238
+ scored.push({ cand, score: Math.round(score * 100) / 100, semScore, structScore, textScore });
239
+ }
240
+ scored.sort((a, b) => b.score - a.score);
241
+ const top = scored.slice(0, limit);
242
+ const withVectors = top.filter((s) => s.cand.embedding != null && !s.cand.embeddingStale).length;
243
+ let searchMode;
244
+ if (input.structureOnly || !deps.embedder || withVectors === 0)
245
+ searchMode = "structural";
246
+ else if (withVectors === top.length)
247
+ searchMode = "semantic";
248
+ else
249
+ searchMode = "mixed";
250
+ const results = top.map((s) => ({
251
+ name: s.cand.name,
252
+ scope: s.cand.scope,
253
+ purpose: s.cand.purpose,
254
+ tags: s.cand.tags,
255
+ phaseSignature: s.cand.phaseSignature,
256
+ phaseCount: s.cand.phaseCount,
257
+ generality: s.cand.generality,
258
+ reuseCount: s.cand.reuseCount,
259
+ version: s.cand.version,
260
+ score: s.score,
261
+ why: buildWhy({ semScore: s.semScore, structScore: s.structScore, textScore: s.textScore, searchMode }),
262
+ reuseHint: buildReuseHint({ score: s.score, argCount: argCountOf(s.cand.def) }),
263
+ }));
264
+ return {
265
+ results,
266
+ searchMode,
267
+ embedder: deps.embedder?.model,
268
+ counts: { scanned: flows.length, withVectors },
269
+ };
270
+ }
271
+ /** Pure cosine similarity. Zero-dep. Accepts non-normalized vectors. */
272
+ export function cosine(a, b) {
273
+ const n = Math.min(a.length, b.length);
274
+ if (n === 0)
275
+ return 0;
276
+ let dot = 0;
277
+ let normA = 0;
278
+ let normB = 0;
279
+ for (let i = 0; i < n; i++) {
280
+ const x = a[i];
281
+ const y = b[i];
282
+ if (!Number.isFinite(x) || !Number.isFinite(y))
283
+ continue;
284
+ dot += x * y;
285
+ normA += x * x;
286
+ normB += y * y;
287
+ }
288
+ if (normA === 0 || normB === 0)
289
+ return 0;
290
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
291
+ }
292
+ /** Bump reuseCount for a flow by name (RFC §6 reuse flywheel).
293
+ * Phase 1: structural-only; the caller (tool handler) decides whether to
294
+ * bump based on a `reusedFromSearch` flag. Returns the new count or null if
295
+ * the flow has no sidecar yet. The actual sidecar write is done by
296
+ * `bumpReuseInSidecar` in store.ts under withLock. */
297
+ export { getFlow };
298
+ //# sourceMappingURL=search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search.js","sourceRoot":"","sources":["../../src/library/search.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE3D,OAAO,EACN,iBAAiB,EACjB,qBAAqB,EACrB,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skflow accumulate, retrieve, and iteratively generalize
5
+ * saved flows. Phase 1 (this module) defines the data shapes and the
6
+ * host-neutral interfaces; the runtime logic (meta derivation, search ranking)
7
+ * lives in `meta.ts` / `search.ts`, and persistence (sidecar `.meta.json`)
8
+ * lives in `store.ts`.
9
+ *
10
+ * Design refs: docs/rfc-library-reuse.md (§3 data format, §4 embedder, §5
11
+ * search). Embedding support is Phase 2 — Phase 1 ships with structural /
12
+ * keyword search only and every embedding field is optional.
13
+ */
14
+ import type { Taskflow } from "../schema.ts";
15
+ /** Library-side settings, nested under `settings.json → taskflow.library`. */
16
+ export interface LibrarySettings {
17
+ /** Master switch. Default true. When false, search/save-meta are no-ops. */
18
+ enabled: boolean;
19
+ /** Which scopes to search: "project" | "user" | "both" (default both). */
20
+ scope: "project" | "user" | "both";
21
+ /** Optional blend weights for mixed search ranking (Phase 2). */
22
+ searchWeights?: {
23
+ semantic: number;
24
+ structural: number;
25
+ textual: number;
26
+ };
27
+ /** Optional Phase-3 auto-prune threshold. */
28
+ maxFlows?: number;
29
+ }
30
+ export declare const DEFAULT_LIBRARY_SETTINGS: LibrarySettings;
31
+ /** The sidecar `.meta.json` record. Persisted next to a flow file. */
32
+ export interface FlowMeta {
33
+ schemaVersion: 1;
34
+ /** Agent-provided (optional). */
35
+ purpose?: string;
36
+ tags?: string[];
37
+ notes?: string;
38
+ /** Auto-derived at save time. */
39
+ phaseSignature: string;
40
+ phaseCount: number;
41
+ agentUsage: string[];
42
+ generality: number;
43
+ argShape?: Record<string, string>;
44
+ /** Reuse flywheel. */
45
+ reuseCount: number;
46
+ lastUsedAt: number | null;
47
+ createdAt: number;
48
+ version: number;
49
+ derivedFrom?: string;
50
+ /** Embedding (Phase 2; always optional / may be null). */
51
+ embeddingModel?: string;
52
+ embeddingDim?: number;
53
+ embedding?: number[] | null;
54
+ embeddedAt?: number | null;
55
+ }
56
+ /** A candidate resolved for search: live-derived structural fields + trusted
57
+ * sidecar fields (purpose/tags/...) + embedding gated on signature match.
58
+ * (RFC §5.2.2 staleness detection.) */
59
+ export interface ResolvedCandidate {
60
+ name: string;
61
+ scope: "user" | "project";
62
+ def: Taskflow;
63
+ phaseSignature: string;
64
+ phaseCount: number;
65
+ agentUsage: string[];
66
+ generality: number;
67
+ purpose?: string;
68
+ tags?: string[];
69
+ notes?: string;
70
+ reuseCount: number;
71
+ version: number;
72
+ derivedFrom?: string;
73
+ embedding: number[] | null;
74
+ embeddingStale: boolean;
75
+ }
76
+ export interface SearchResult {
77
+ name: string;
78
+ scope: "user" | "project";
79
+ purpose?: string;
80
+ tags?: string[];
81
+ phaseSignature: string;
82
+ phaseCount: number;
83
+ generality: number;
84
+ reuseCount: number;
85
+ version: number;
86
+ score: number;
87
+ why: string;
88
+ reuseHint: string;
89
+ }
90
+ export interface SearchResponse {
91
+ results: SearchResult[];
92
+ searchMode: "semantic" | "structural" | "mixed";
93
+ embedder?: string;
94
+ counts: {
95
+ scanned: number;
96
+ withVectors: number;
97
+ };
98
+ }
99
+ /** Input to searchLibrary(). */
100
+ export interface SearchInput {
101
+ query: string;
102
+ limit?: number;
103
+ structureOnly?: boolean;
104
+ minScore?: number;
105
+ scope?: "project" | "user" | "both";
106
+ phaseSignatureHint?: string;
107
+ phaseCountHint?: number;
108
+ }
109
+ /** The minimal host-neutral dependency the library functions need.
110
+ * Embedder is Phase 2; Phase 1 leaves it undefined and search degrades to
111
+ * structural/keyword (RFC §4.3, A2: stays OUT of RuntimeDeps). */
112
+ export interface LibraryDeps {
113
+ embedder?: {
114
+ embed(text: string): Promise<number[]>;
115
+ readonly model: string;
116
+ readonly dim: number;
117
+ };
118
+ settings: LibrarySettings;
119
+ cwd: string;
120
+ }
121
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/library/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC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AAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;IACpC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;mEAEmE;AACnE,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,EAAE;QACV,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;KACrB,CAAC;IACF,QAAQ,EAAE,eAAe,CAAC;IAC1B,GAAG,EAAE,MAAM,CAAC;CACZ"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Library — reusable-flow asset layer types.
3
+ *
4
+ * The library lets taskflow accumulate, retrieve, and iteratively generalize
5
+ * saved flows. Phase 1 (this module) defines the data shapes and the
6
+ * host-neutral interfaces; the runtime logic (meta derivation, search ranking)
7
+ * lives in `meta.ts` / `search.ts`, and persistence (sidecar `.meta.json`)
8
+ * lives in `store.ts`.
9
+ *
10
+ * Design refs: docs/rfc-library-reuse.md (§3 data format, §4 embedder, §5
11
+ * search). Embedding support is Phase 2 — Phase 1 ships with structural /
12
+ * keyword search only and every embedding field is optional.
13
+ */
14
+ export const DEFAULT_LIBRARY_SETTINGS = {
15
+ enabled: true,
16
+ scope: "both",
17
+ };
18
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/library/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAgBH,MAAM,CAAC,MAAM,wBAAwB,GAAoB;IACxD,OAAO,EAAE,IAAI;IACb,KAAK,EAAE,MAAM;CACb,CAAC"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Reflexion memory for loop phases — pure helpers.
3
+ *
4
+ * When a loop phase sets `reflexion: true`, each iteration i > 1 receives a
5
+ * `{reflexion}` placeholder carrying a structured failure summary of the
6
+ * immediately-prior iteration: what happened (contract violation / subagent
7
+ * error / until-not-met), the precise diagnostics, and a truncated output
8
+ * snippet. The model iterates WITH the failure signal instead of re-guessing
9
+ * from a bare output (Reflexion, Shinn et al. 2023 — as a declarative field).
10
+ *
11
+ * Pure and total: assembly never throws on any input (the runtime additionally
12
+ * wraps the call fail-open — a reflexion bug must never sink the phase).
13
+ */
14
+ /** Cap on the assembled reflexion block (chars). Keeps the injected context
15
+ * from crowding out the actual task in the iteration prompt. */
16
+ export declare const REFLEXION_MAX_CHARS = 2000;
17
+ /** What iteration 1 sees: there is no prior iteration to reflect on. */
18
+ export declare const REFLEXION_SENTINEL = "_(first iteration \u2014 no prior feedback yet)_";
19
+ /** How the prior iteration ended, for the summary headline. */
20
+ export type ReflexionOutcome = "until-not-met" | "contract-violation" | "subagent-error";
21
+ export interface ReflexionInput {
22
+ /** 1-based index of the PRIOR iteration being summarized. */
23
+ iteration: number;
24
+ outcome: ReflexionOutcome;
25
+ /** The prior iteration's raw output (or error-bearing output on failure). */
26
+ output?: string;
27
+ /** errorMessage of a failed prior iteration (contract diagnostics live here). */
28
+ errorMessage?: string;
29
+ /** The loop's `until` expression (shown when outcome is until-not-met). */
30
+ until?: string;
31
+ }
32
+ /**
33
+ * Build the reflexion summary block injected into the next iteration's prompt.
34
+ * Sections are conditional — no empty headings. Total: never throws.
35
+ */
36
+ export declare function buildReflexionSummary(input: ReflexionInput, maxChars?: number): string;
37
+ /**
38
+ * Pull the per-path diagnostics out of a runOne contract-violation
39
+ * errorMessage ("Output contract violated:\n- $.score: …\n- …").
40
+ * Returns [] for any other error shape.
41
+ */
42
+ export declare function extractContractDiagnostics(errorMessage?: string): string[];
43
+ /** True when the errorMessage carries a contract violation (classification
44
+ * for ReflexionInput.outcome). */
45
+ export declare function isContractViolation(errorMessage?: string): boolean;
46
+ //# sourceMappingURL=reflexion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reflexion.d.ts","sourceRoot":"","sources":["../src/reflexion.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;iEACiE;AACjE,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAExC,wEAAwE;AACxE,eAAO,MAAM,kBAAkB,qDAAgD,CAAC;AAEhF,+DAA+D;AAC/D,MAAM,MAAM,gBAAgB,GACzB,eAAe,GACf,oBAAoB,GACpB,gBAAgB,CAAC;AAEpB,MAAM,WAAW,cAAc;IAC9B,6DAA6D;IAC7D,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,gBAAgB,CAAC;IAC1B,6EAA6E;IAC7E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iFAAiF;IACjF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,cAAc,EAAE,QAAQ,GAAE,MAA4B,GAAG,MAAM,CAkC3G;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAO1E;AAED;mCACmC;AACnC,wBAAgB,mBAAmB,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAElE"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Reflexion memory for loop phases — pure helpers.
3
+ *
4
+ * When a loop phase sets `reflexion: true`, each iteration i > 1 receives a
5
+ * `{reflexion}` placeholder carrying a structured failure summary of the
6
+ * immediately-prior iteration: what happened (contract violation / subagent
7
+ * error / until-not-met), the precise diagnostics, and a truncated output
8
+ * snippet. The model iterates WITH the failure signal instead of re-guessing
9
+ * from a bare output (Reflexion, Shinn et al. 2023 — as a declarative field).
10
+ *
11
+ * Pure and total: assembly never throws on any input (the runtime additionally
12
+ * wraps the call fail-open — a reflexion bug must never sink the phase).
13
+ */
14
+ /** Cap on the assembled reflexion block (chars). Keeps the injected context
15
+ * from crowding out the actual task in the iteration prompt. */
16
+ export const REFLEXION_MAX_CHARS = 2000;
17
+ /** What iteration 1 sees: there is no prior iteration to reflect on. */
18
+ export const REFLEXION_SENTINEL = "_(first iteration — no prior feedback yet)_";
19
+ /**
20
+ * Build the reflexion summary block injected into the next iteration's prompt.
21
+ * Sections are conditional — no empty headings. Total: never throws.
22
+ */
23
+ export function buildReflexionSummary(input, maxChars = REFLEXION_MAX_CHARS) {
24
+ const lines = [`## Reflexion: iteration ${input.iteration} (prior)`];
25
+ switch (input.outcome) {
26
+ case "contract-violation":
27
+ lines.push("- Outcome: FAILED — output contract violated");
28
+ break;
29
+ case "subagent-error":
30
+ lines.push("- Outcome: FAILED — subagent error");
31
+ break;
32
+ case "until-not-met":
33
+ lines.push("- Outcome: succeeded, but the stop condition was not met");
34
+ if (input.until)
35
+ lines.push(`- Stop condition still false: \`${oneLine(input.until, 200)}\``);
36
+ break;
37
+ }
38
+ const diags = extractContractDiagnostics(input.errorMessage);
39
+ if (diags.length > 0) {
40
+ lines.push("- Contract diagnostics:");
41
+ for (const d of diags)
42
+ lines.push(` - ${oneLine(d, 200)}`);
43
+ }
44
+ else if (input.outcome !== "until-not-met" && input.errorMessage) {
45
+ lines.push(`- Error: ${oneLine(input.errorMessage, 400)}`);
46
+ }
47
+ lines.push("- Fix the issues above in this iteration.");
48
+ const head = lines.join("\n");
49
+ const output = (input.output ?? "").trim();
50
+ if (!output)
51
+ return truncateBlock(head, maxChars);
52
+ // Fit the output snippet into whatever budget the headline left over.
53
+ const frame = "\n- Prior output (truncated):\n```\n";
54
+ const close = "\n```";
55
+ const budget = maxChars - head.length - frame.length - close.length;
56
+ if (budget < 40)
57
+ return truncateBlock(head, maxChars); // no room for a useful snippet
58
+ const snippet = truncateMiddle(output, budget);
59
+ return `${head}${frame}${snippet}${close}`;
60
+ }
61
+ /**
62
+ * Pull the per-path diagnostics out of a runOne contract-violation
63
+ * errorMessage ("Output contract violated:\n- $.score: …\n- …").
64
+ * Returns [] for any other error shape.
65
+ */
66
+ export function extractContractDiagnostics(errorMessage) {
67
+ if (!errorMessage || !errorMessage.startsWith("Output contract violated"))
68
+ return [];
69
+ return errorMessage
70
+ .split("\n")
71
+ .slice(1)
72
+ .map((l) => l.replace(/^-\s*/, "").trim())
73
+ .filter((l) => l.length > 0);
74
+ }
75
+ /** True when the errorMessage carries a contract violation (classification
76
+ * for ReflexionInput.outcome). */
77
+ export function isContractViolation(errorMessage) {
78
+ return typeof errorMessage === "string" && errorMessage.startsWith("Output contract violated");
79
+ }
80
+ /** Keep first ~60% and last ~30% of an over-budget string (errors often sit
81
+ * at the end; intent at the start). */
82
+ function truncateMiddle(s, budget) {
83
+ if (s.length <= budget)
84
+ return s;
85
+ const marker = `\n…[truncated ${s.length - budget} chars]…\n`;
86
+ const usable = budget - marker.length;
87
+ if (usable < 20)
88
+ return s.slice(0, Math.max(0, budget));
89
+ const headLen = Math.floor(usable * 0.65);
90
+ const tailLen = usable - headLen;
91
+ return s.slice(0, headLen) + marker + s.slice(s.length - tailLen);
92
+ }
93
+ function truncateBlock(s, maxChars) {
94
+ return s.length <= maxChars ? s : `${s.slice(0, maxChars - 1)}…`;
95
+ }
96
+ function oneLine(s, max) {
97
+ const flat = s.replace(/\s+/g, " ").trim();
98
+ return flat.length <= max ? flat : `${flat.slice(0, max - 1)}…`;
99
+ }
100
+ //# sourceMappingURL=reflexion.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reflexion.js","sourceRoot":"","sources":["../src/reflexion.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;iEACiE;AACjE,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAExC,wEAAwE;AACxE,MAAM,CA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