@hassangameryt/freeflow 0.7.1 → 0.7.3
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/README.md +153 -128
- package/capabilities/cognitive-routing/SKILL.md +126 -274
- package/command-surface.json +7 -1
- package/gemini-extension.json +1 -1
- package/package.json +4 -4
- package/pi-extension/dist/cognitive-routing-v2/budget.js +42 -0
- package/pi-extension/dist/cognitive-routing-v2/config.js +136 -0
- package/pi-extension/dist/cognitive-routing-v2/projection.js +330 -0
- package/pi-extension/dist/cognitive-routing-v2/render.js +252 -0
- package/pi-extension/dist/cognitive-routing-v2/runtime.js +2181 -0
- package/pi-extension/dist/cognitive-routing-v2/schemas.js +173 -0
- package/pi-extension/dist/cognitive-routing-v2/state.js +828 -0
- package/pi-extension/dist/cognitive-routing-v2/tools.js +60 -0
- package/pi-extension/dist/cognitive-routing-v2/types.js +48 -0
- package/pi-extension/dist/context-virtualization/runtime.js +29 -7
- package/pi-extension/dist/freeflow-context/tool.js +12 -6
- package/pi-extension/dist/index.js +302 -626
- package/pi-extension/dist/provider-support/astra/adapter.js +110 -0
- package/pi-extension/dist/provider-support/astra/history.js +125 -0
- package/pi-extension/dist/provider-support/astra/index.js +11 -0
- package/pi-extension/dist/provider-support/astra/session-state.js +114 -0
- package/pi-extension/dist/provider-support/index.js +4 -0
- package/pi-extension/dist/runtime/request-history.js +216 -0
- package/pi-extension/dist/runtime/runtime-context.js +85 -16
- package/pi-extension/dist/session-sources/events.js +217 -0
- package/pi-extension/dist/session-sources/provenance.js +32 -0
- package/pi-extension/dist/session-sources/read-only-session.js +148 -0
- package/pi-extension/dist/session-sources/sources.js +277 -0
- package/pi-extension/dist/settings/settings-ui.js +274 -147
- package/pi-extension/src/cognitive-routing-v2/budget.ts +42 -0
- package/pi-extension/src/cognitive-routing-v2/config.ts +173 -0
- package/pi-extension/src/cognitive-routing-v2/projection.ts +375 -0
- package/pi-extension/src/cognitive-routing-v2/render.ts +277 -0
- package/pi-extension/src/cognitive-routing-v2/runtime.ts +2241 -0
- package/pi-extension/src/cognitive-routing-v2/schemas.ts +180 -0
- package/pi-extension/src/cognitive-routing-v2/state.ts +839 -0
- package/pi-extension/src/cognitive-routing-v2/tools.ts +62 -0
- package/pi-extension/src/cognitive-routing-v2/types.ts +254 -0
- package/pi-extension/src/context-virtualization/runtime.ts +30 -8
- package/pi-extension/src/freeflow-context/tool.ts +12 -6
- package/pi-extension/src/index.ts +308 -675
- package/pi-extension/src/provider-support/astra/adapter.ts +108 -0
- package/pi-extension/src/provider-support/astra/history.ts +145 -0
- package/pi-extension/src/provider-support/astra/index.ts +12 -0
- package/pi-extension/src/provider-support/astra/session-state.ts +113 -0
- package/pi-extension/src/provider-support/index.ts +5 -0
- package/pi-extension/src/runtime/request-history.ts +243 -0
- package/pi-extension/src/runtime/runtime-context.ts +100 -17
- package/pi-extension/src/session-sources/events.ts +230 -0
- package/pi-extension/src/session-sources/provenance.ts +39 -0
- package/pi-extension/src/session-sources/read-only-session.ts +170 -0
- package/pi-extension/src/session-sources/sources.ts +334 -0
- package/pi-extension/src/settings/settings-ui.ts +311 -158
- package/pi-extension/tests/cache-reuse/history.test.js +117 -0
- package/pi-extension/tests/cache-reuse/native.test.js +91 -0
- package/pi-extension/tests/cache-reuse/settings.test.js +211 -0
- package/pi-extension/tests/cognitive-routing-v2/communication.test.js +577 -0
- package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +183 -0
- package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +557 -0
- package/pi-extension/tests/cognitive-routing-v2/native.test.js +474 -0
- package/pi-extension/tests/cognitive-routing-v2/performance.test.js +87 -0
- package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +300 -0
- package/pi-extension/tests/cognitive-routing-v2/projection.test.js +241 -0
- package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +1034 -0
- package/pi-extension/tests/cognitive-routing-v2/render.test.js +244 -0
- package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +423 -0
- package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +521 -0
- package/pi-extension/tests/cognitive-routing-v2/state.test.js +586 -0
- package/pi-extension/tests/context-virtualization/extension.test.js +33 -7
- package/pi-extension/tests/context-virtualization/runtime.test.js +17 -3
- package/pi-extension/tests/fixtures/routing-native.js +191 -0
- package/pi-extension/tests/integration/mode-free-core.test.js +6 -4
- package/pi-extension/tests/integration/pi-extension.test.js +655 -59
- package/pi-extension/tests/integration/prompt-architecture.test.js +127 -30
- package/pi-extension/tests/integration/unaffected-regressions.test.js +78 -11
- package/pi-extension/tests/provider-support/astra-boundaries.test.js +75 -0
- package/pi-extension/tests/provider-support/astra.test.js +306 -0
- package/pi-extension/tests/provider-support/cli.test.js +92 -0
- package/pi-extension/tests/provider-support/native.test.js +183 -0
- package/plugin.json +1 -1
- package/runtime/prompts/cognitive-routing.md +4 -5
- package/runtime/prompts/core.md +51 -45
- package/runtime/prompts/interaction-contract.md +5 -5
- package/skills/action-selection/SKILL.md +57 -97
- package/skills/design-for-depth/SKILL.md +58 -193
- package/skills/design-for-depth/references/implementation-decisions.md +76 -0
- package/skills/diagnose-failure/SKILL.md +64 -196
- package/skills/discuss/SKILL.md +64 -123
- package/skills/discuss/references/discussion-continuity.md +7 -3
- package/skills/execute-work/SKILL.md +69 -88
- package/skills/execute-work/references/execute-work-edges.md +9 -3
- package/skills/handoff/SKILL.md +44 -54
- package/skills/handoff/references/handoff-templates.md +15 -6
- package/skills/review-artifact/SKILL.md +80 -127
- package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
- package/skills/review-work/SKILL.md +65 -115
- package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
- package/skills/simplify-code/SKILL.md +47 -100
- package/skills/track-work/SKILL.md +128 -119
- package/skills/track-work/references/working-record-format.md +14 -2
- package/skills/verify-work/SKILL.md +58 -62
- package/skills/verify-work/references/integration-evidence.md +4 -2
- package/skills/verify-work/references/test-design.md +89 -0
- package/skills/workflow/SKILL.md +73 -119
- package/skills/write-plan/SKILL.md +46 -77
- package/skills/write-plan/references/plan-shapes.md +5 -5
- package/skills/write-spec/SKILL.md +51 -63
- package/skills/write-spec/references/artifact-standards.md +2 -2
- package/skills/write-spec/references/decision-records.md +3 -2
- package/skills/write-spec/references/spec-shapes.md +15 -0
- package/pi-extension/dist/cognitive-routing/commands.js +0 -96
- package/pi-extension/dist/cognitive-routing/config.js +0 -232
- package/pi-extension/dist/cognitive-routing/controller.js +0 -1292
- package/pi-extension/dist/cognitive-routing/history.js +0 -451
- package/pi-extension/dist/cognitive-routing/host.js +0 -188
- package/pi-extension/dist/cognitive-routing/pi-routing-session.js +0 -414
- package/pi-extension/dist/cognitive-routing/pi-session-control.js +0 -320
- package/pi-extension/dist/cognitive-routing/runtime.js +0 -43
- package/pi-extension/dist/cognitive-routing/tool.js +0 -212
- package/pi-extension/dist/cognitive-routing/types.js +0 -6
- package/pi-extension/src/cognitive-routing/commands.ts +0 -129
- package/pi-extension/src/cognitive-routing/config.ts +0 -303
- package/pi-extension/src/cognitive-routing/controller.ts +0 -1628
- package/pi-extension/src/cognitive-routing/history.ts +0 -650
- package/pi-extension/src/cognitive-routing/host.ts +0 -266
- package/pi-extension/src/cognitive-routing/pi-routing-session.ts +0 -538
- package/pi-extension/src/cognitive-routing/pi-session-control.ts +0 -444
- package/pi-extension/src/cognitive-routing/runtime.ts +0 -57
- package/pi-extension/src/cognitive-routing/tool.ts +0 -273
- package/pi-extension/src/cognitive-routing/types.ts +0 -89
- package/pi-extension/tests/cognitive-routing/commands.test.js +0 -134
- package/pi-extension/tests/cognitive-routing/controller.test.js +0 -1128
- package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +0 -1142
- package/pi-extension/tests/cognitive-routing/history.test.js +0 -274
- package/pi-extension/tests/cognitive-routing/host-identity.test.js +0 -63
- package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +0 -434
- package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +0 -174
- package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +0 -91
- package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +0 -279
- package/pi-extension/tests/cognitive-routing/tool.test.js +0 -230
- package/skills/tdd/SKILL.md +0 -143
- package/skills/tdd/references/test-design.md +0 -96
- /package/pi-extension/tests/{cognitive-routing/host-fixture.js → fixtures/pi-host.js} +0 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { assemble, EFFORTS } from "./history.js";
|
|
2
|
+
import { SessionState } from "./session-state.js";
|
|
3
|
+
export function requestKey(payload, model) {
|
|
4
|
+
if (
|
|
5
|
+
!payload ||
|
|
6
|
+
payload.model !== "gpt-6-astra" ||
|
|
7
|
+
model?.id !== payload.model ||
|
|
8
|
+
payload.store !== false ||
|
|
9
|
+
!Array.isArray(payload.input) ||
|
|
10
|
+
!EFFORTS.includes(payload.reasoning?.effort) ||
|
|
11
|
+
payload.previous_response_id ||
|
|
12
|
+
payload.conversation ||
|
|
13
|
+
payload.context_management ||
|
|
14
|
+
(payload.truncation && payload.truncation !== "disabled") ||
|
|
15
|
+
(payload.reasoning.mode && payload.reasoning.mode !== "standard") ||
|
|
16
|
+
payload.agents ||
|
|
17
|
+
payload.input.some((x) => x?.type === "configuration_update" || x?.type === "compaction_trigger")
|
|
18
|
+
)
|
|
19
|
+
return;
|
|
20
|
+
const codex = model.provider === "openai-codex" && model.api === "openai-codex-responses";
|
|
21
|
+
const api = model.provider === "openai" && model.api === "openai-responses";
|
|
22
|
+
if (!codex && !api) return;
|
|
23
|
+
if (model.baseUrl !== undefined && typeof model.baseUrl !== "string") return;
|
|
24
|
+
const base = (model.baseUrl ?? (codex ? "https://chatgpt.com/backend-api" : "https://api.openai.com/v1")).replace(
|
|
25
|
+
/\/+$/,
|
|
26
|
+
"",
|
|
27
|
+
);
|
|
28
|
+
const allowed = codex
|
|
29
|
+
? [
|
|
30
|
+
"https://chatgpt.com/backend-api",
|
|
31
|
+
"https://chatgpt.com/backend-api/codex",
|
|
32
|
+
"https://chatgpt.com/backend-api/codex/responses",
|
|
33
|
+
]
|
|
34
|
+
: ["https://api.openai.com/v1"];
|
|
35
|
+
if (!allowed.includes(base)) return;
|
|
36
|
+
return `${model.provider}/${model.api}/${model.id}`;
|
|
37
|
+
}
|
|
38
|
+
export class AstraAdapter {
|
|
39
|
+
pi;
|
|
40
|
+
session;
|
|
41
|
+
generation = 0;
|
|
42
|
+
compacting = false;
|
|
43
|
+
queue = Promise.resolve();
|
|
44
|
+
statusSignature;
|
|
45
|
+
constructor(pi) {
|
|
46
|
+
this.pi = pi;
|
|
47
|
+
}
|
|
48
|
+
reset(ctx) {
|
|
49
|
+
this.generation++;
|
|
50
|
+
this.session = undefined;
|
|
51
|
+
this.compacting = false;
|
|
52
|
+
this.status(ctx, undefined);
|
|
53
|
+
}
|
|
54
|
+
setCompacting(value) {
|
|
55
|
+
this.compacting = value;
|
|
56
|
+
}
|
|
57
|
+
status(ctx, label) {
|
|
58
|
+
if (this.statusSignature === label) return;
|
|
59
|
+
this.statusSignature = label;
|
|
60
|
+
// Diagnostics must never turn a completed payload transformation into an exception.
|
|
61
|
+
try {
|
|
62
|
+
ctx.ui?.setStatus?.("freeflow-astra-effort", label);
|
|
63
|
+
} catch {}
|
|
64
|
+
}
|
|
65
|
+
async adapt(payload, ctx) {
|
|
66
|
+
const generation = this.generation;
|
|
67
|
+
const operation = this.queue.then(async () => {
|
|
68
|
+
const key = requestKey(payload, ctx.model);
|
|
69
|
+
if (generation !== this.generation || this.compacting || !key) {
|
|
70
|
+
this.status(ctx, undefined);
|
|
71
|
+
return payload;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
const reader = ctx.sessionManager;
|
|
75
|
+
if (
|
|
76
|
+
typeof this.pi.appendEntry !== "function" ||
|
|
77
|
+
!reader?.getLeafId ||
|
|
78
|
+
!reader.getSessionId ||
|
|
79
|
+
!reader.getSessionFile
|
|
80
|
+
)
|
|
81
|
+
throw new Error("Native session persistence unavailable");
|
|
82
|
+
const id = reader.getSessionId(),
|
|
83
|
+
file = reader.getSessionFile();
|
|
84
|
+
if (!this.session || this.session.id !== id || this.session.file !== file)
|
|
85
|
+
this.session = { id, file, store: new SessionState(this.pi, reader) };
|
|
86
|
+
const store = this.session.store,
|
|
87
|
+
basis = reader.getLeafId();
|
|
88
|
+
const records = await store.records();
|
|
89
|
+
if (
|
|
90
|
+
generation !== this.generation ||
|
|
91
|
+
reader.getLeafId() !== basis ||
|
|
92
|
+
this.session?.store !== store ||
|
|
93
|
+
key !== requestKey(payload, ctx.model)
|
|
94
|
+
)
|
|
95
|
+
throw new Error("Astra request changed during preparation");
|
|
96
|
+
const result = assemble(payload, key, store.generation(), basis, records);
|
|
97
|
+
if (result.record) store.append(result.record);
|
|
98
|
+
this.status(ctx, `Astra ${result.effective} · cache baseline ${result.baseline}`);
|
|
99
|
+
return result.payload;
|
|
100
|
+
} catch {
|
|
101
|
+
// Pi swallows hook exceptions. Return the untouched full-history request,
|
|
102
|
+
// including its requested effort, instead of a partially pinned request.
|
|
103
|
+
this.status(ctx, "Astra cache adaptation unavailable · native effort");
|
|
104
|
+
return payload;
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
this.queue = operation.catch(() => {});
|
|
108
|
+
return operation;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
export const ENTRY_TYPE = "freeflow-astra-effort-v1";
|
|
3
|
+
export const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
4
|
+
export const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
5
|
+
const digest = (x) => typeof x === "string" && /^[a-f0-9]{64}$/.test(x);
|
|
6
|
+
const effort = (x) => EFFORTS.includes(x);
|
|
7
|
+
const identity = (x) => typeof x === "string" && x.length > 0 && x.length <= 1024;
|
|
8
|
+
export function parseAttempt(value) {
|
|
9
|
+
if (
|
|
10
|
+
!value ||
|
|
11
|
+
value.version !== 1 ||
|
|
12
|
+
!identity(value.id) ||
|
|
13
|
+
!(value.basis === null || identity(value.basis)) ||
|
|
14
|
+
!identity(value.key) ||
|
|
15
|
+
!identity(value.generation) ||
|
|
16
|
+
!digest(value.envelope) ||
|
|
17
|
+
!digest(value.inputHash) ||
|
|
18
|
+
!effort(value.baseline) ||
|
|
19
|
+
!effort(value.effective) ||
|
|
20
|
+
!(value.parent === null || identity(value.parent)) ||
|
|
21
|
+
!Number.isSafeInteger(value.length) ||
|
|
22
|
+
value.length < 0 ||
|
|
23
|
+
(value.update !== undefined &&
|
|
24
|
+
(!value.update ||
|
|
25
|
+
!Number.isSafeInteger(value.update.at) ||
|
|
26
|
+
value.update.at < 0 ||
|
|
27
|
+
value.update.at > value.length ||
|
|
28
|
+
!digest(value.update.prefixHash) ||
|
|
29
|
+
!effort(value.update.effort))) ||
|
|
30
|
+
Object.keys(value).some(
|
|
31
|
+
(k) =>
|
|
32
|
+
![
|
|
33
|
+
"version",
|
|
34
|
+
"id",
|
|
35
|
+
"basis",
|
|
36
|
+
"key",
|
|
37
|
+
"generation",
|
|
38
|
+
"envelope",
|
|
39
|
+
"baseline",
|
|
40
|
+
"effective",
|
|
41
|
+
"parent",
|
|
42
|
+
"length",
|
|
43
|
+
"inputHash",
|
|
44
|
+
"update",
|
|
45
|
+
].includes(k),
|
|
46
|
+
)
|
|
47
|
+
)
|
|
48
|
+
throw new Error("Invalid Astra effort history");
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
// Hash complete serialized items, including opaque reasoning; never persist their bodies.
|
|
52
|
+
export function prefixHashes(input) {
|
|
53
|
+
const result = [hash([])];
|
|
54
|
+
for (const item of input) result.push(hash([result.at(-1), item]));
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
export function envelopeHash(payload) {
|
|
58
|
+
const { input: _input, prompt_cache_key: _key, max_output_tokens: _max, stream: _stream, ...rest } = payload;
|
|
59
|
+
const { effort: _effort, ...reasoning } = rest.reasoning;
|
|
60
|
+
return hash({ ...rest, reasoning });
|
|
61
|
+
}
|
|
62
|
+
export function assemble(payload, key, generation, basis, records) {
|
|
63
|
+
const hashes = prefixHashes(payload.input),
|
|
64
|
+
envelope = envelopeHash(payload);
|
|
65
|
+
const applicable = records.filter((r) => r.key === key && r.generation === generation);
|
|
66
|
+
const compatible = applicable.filter((r) => r.envelope === envelope && hashes[r.length] === r.inputHash);
|
|
67
|
+
const prior = compatible.reduce((best, r) => (!best || r.length >= best.length ? r : best), undefined);
|
|
68
|
+
const baseline = prior?.baseline ?? applicable[0]?.baseline ?? payload.reasoning.effort;
|
|
69
|
+
const desired = payload.reasoning.effort;
|
|
70
|
+
const byId = new Map(records.map((r) => [r.id, r]));
|
|
71
|
+
const updates = [];
|
|
72
|
+
const seen = new Set();
|
|
73
|
+
let cursor = prior;
|
|
74
|
+
while (cursor) {
|
|
75
|
+
if (seen.has(cursor.id)) throw new Error("Cyclic Astra history");
|
|
76
|
+
seen.add(cursor.id);
|
|
77
|
+
if (cursor.update) {
|
|
78
|
+
if (hashes[cursor.update.at] !== cursor.update.prefixHash) throw new Error("Astra anchor changed");
|
|
79
|
+
updates.unshift(cursor.update);
|
|
80
|
+
}
|
|
81
|
+
if (cursor.parent === null) break;
|
|
82
|
+
const parent = byId.get(cursor.parent);
|
|
83
|
+
if (!parent || parent.key !== key || parent.generation !== generation || parent.baseline !== baseline)
|
|
84
|
+
throw new Error("Astra history parent unavailable");
|
|
85
|
+
cursor = parent;
|
|
86
|
+
}
|
|
87
|
+
let update;
|
|
88
|
+
if (desired !== (prior?.effective ?? baseline)) {
|
|
89
|
+
// Only insert before a new user item. Within a tool loop, append after all completed exchanges.
|
|
90
|
+
const last = payload.input.length - 1;
|
|
91
|
+
const at = payload.input[last]?.role === "user" && last >= (prior?.length ?? 0) ? last : payload.input.length;
|
|
92
|
+
update = { at, prefixHash: hashes[at], effort: desired };
|
|
93
|
+
if (updates.at(-1)?.at === at) throw new Error("Adjacent Astra effort updates");
|
|
94
|
+
updates.push(update);
|
|
95
|
+
}
|
|
96
|
+
if (updates.some((u, i) => i > 0 && u.at <= updates[i - 1].at)) throw new Error("Invalid Astra update order");
|
|
97
|
+
const output = structuredClone(payload);
|
|
98
|
+
output.input = [];
|
|
99
|
+
let nextUpdate = 0;
|
|
100
|
+
for (let i = 0; i <= payload.input.length; i++) {
|
|
101
|
+
if (updates[nextUpdate]?.at === i) {
|
|
102
|
+
output.input.push({ type: "configuration_update", reasoning: { effort: updates[nextUpdate++].effort } });
|
|
103
|
+
}
|
|
104
|
+
if (i < payload.input.length) output.input.push(structuredClone(payload.input[i]));
|
|
105
|
+
}
|
|
106
|
+
output.reasoning.effort = baseline;
|
|
107
|
+
const identical = prior?.length === payload.input.length && prior.effective === desired;
|
|
108
|
+
const record = identical
|
|
109
|
+
? undefined
|
|
110
|
+
: {
|
|
111
|
+
version: 1,
|
|
112
|
+
id: randomUUID(),
|
|
113
|
+
basis,
|
|
114
|
+
key,
|
|
115
|
+
generation,
|
|
116
|
+
envelope,
|
|
117
|
+
baseline,
|
|
118
|
+
effective: desired,
|
|
119
|
+
parent: prior?.id ?? null,
|
|
120
|
+
length: payload.input.length,
|
|
121
|
+
inputHash: hashes.at(-1),
|
|
122
|
+
...(update ? { update } : {}),
|
|
123
|
+
};
|
|
124
|
+
return { payload: output, record, baseline, effective: desired, rebased: !prior && applicable.length > 0 };
|
|
125
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AstraAdapter } from "./adapter.js";
|
|
2
|
+
export function registerAstraSupport(pi) {
|
|
3
|
+
const adapter = new AstraAdapter(pi);
|
|
4
|
+
pi.on("session_start", (_event, ctx) => adapter.reset(ctx));
|
|
5
|
+
pi.on("session_shutdown", (_event, ctx) => adapter.reset(ctx));
|
|
6
|
+
pi.on("session_tree", (_event, ctx) => adapter.reset(ctx));
|
|
7
|
+
pi.on("session_before_compact", () => adapter.setCompacting(true));
|
|
8
|
+
pi.on("session_compact", (_event, ctx) => adapter.reset(ctx));
|
|
9
|
+
pi.on("session_compact_failed", () => adapter.setCompacting(false));
|
|
10
|
+
pi.on("before_provider_request", (event, ctx) => adapter.adapt(event.payload, ctx));
|
|
11
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { activeReadOnlySessionBranch, readOnlySessionSnapshot } from "../../session-sources/read-only-session.js";
|
|
2
|
+
import { ENTRY_TYPE, parseAttempt } from "./history.js";
|
|
3
|
+
export class SessionState {
|
|
4
|
+
pi;
|
|
5
|
+
reader;
|
|
6
|
+
acknowledged = new Map();
|
|
7
|
+
fault;
|
|
8
|
+
constructor(pi, reader) {
|
|
9
|
+
this.pi = pi;
|
|
10
|
+
this.reader = reader;
|
|
11
|
+
}
|
|
12
|
+
branch() {
|
|
13
|
+
const entries = this.reader.getBranch();
|
|
14
|
+
let parent = null;
|
|
15
|
+
const seen = new Set();
|
|
16
|
+
for (const entry of entries) {
|
|
17
|
+
if (!entry.id || seen.has(entry.id) || entry.parentId !== parent)
|
|
18
|
+
throw new Error("Invalid Astra session ancestry");
|
|
19
|
+
seen.add(entry.id);
|
|
20
|
+
parent = entry.id;
|
|
21
|
+
}
|
|
22
|
+
if (parent !== this.reader.getLeafId()) throw new Error("Astra session leaf changed");
|
|
23
|
+
return entries;
|
|
24
|
+
}
|
|
25
|
+
async records() {
|
|
26
|
+
if (this.fault) throw new Error(this.fault);
|
|
27
|
+
const branch = this.branch();
|
|
28
|
+
// Model visits are not history replacement. Derive both identities from the
|
|
29
|
+
// selected native ancestry so old v1 records remain readable without rewriting them.
|
|
30
|
+
const boundaries = new Map();
|
|
31
|
+
let epoch = "root",
|
|
32
|
+
legacy = "root",
|
|
33
|
+
model;
|
|
34
|
+
for (const entry of branch) {
|
|
35
|
+
if (entry.type === "compaction" || entry.type === "branch_summary") epoch = legacy = entry.id;
|
|
36
|
+
if (entry.type === "model_change") {
|
|
37
|
+
const next = `${entry.provider}/${entry.modelId}`;
|
|
38
|
+
if (model !== next) legacy = entry.id;
|
|
39
|
+
model = next;
|
|
40
|
+
}
|
|
41
|
+
boundaries.set(entry.id, { epoch, legacy });
|
|
42
|
+
}
|
|
43
|
+
const entries = branch.filter((e) => e.type === "custom" && e.customType === ENTRY_TYPE);
|
|
44
|
+
const records = entries.map((e) => {
|
|
45
|
+
const record = parseAttempt(e.data);
|
|
46
|
+
if (
|
|
47
|
+
record.basis !== e.parentId &&
|
|
48
|
+
!(this.reader.getHeader?.()?.parentSession && !branch.some((entry) => entry.id === record.basis))
|
|
49
|
+
)
|
|
50
|
+
throw new Error("Astra attempt anchor mismatch");
|
|
51
|
+
const boundary = boundaries.get(e.id);
|
|
52
|
+
if (record.generation !== boundary.epoch && record.generation !== boundary.legacy)
|
|
53
|
+
throw new Error("Astra history generation unavailable");
|
|
54
|
+
return { ...record, generation: boundary.epoch };
|
|
55
|
+
});
|
|
56
|
+
if (new Set(records.map((r) => r.id)).size !== records.length) throw new Error("Duplicate Astra attempt");
|
|
57
|
+
const parents = new Map();
|
|
58
|
+
for (const record of records) {
|
|
59
|
+
const parent = record.parent === null ? undefined : parents.get(record.parent);
|
|
60
|
+
if (
|
|
61
|
+
record.parent !== null &&
|
|
62
|
+
(!parent ||
|
|
63
|
+
parent.key !== record.key ||
|
|
64
|
+
parent.generation !== record.generation ||
|
|
65
|
+
parent.envelope !== record.envelope ||
|
|
66
|
+
parent.baseline !== record.baseline ||
|
|
67
|
+
parent.length > record.length)
|
|
68
|
+
)
|
|
69
|
+
throw new Error("Invalid Astra history parent");
|
|
70
|
+
const expected = record.update?.effort ?? parent?.effective ?? record.baseline;
|
|
71
|
+
if (record.effective !== expected || (record.update && record.update.at < (parent?.length ?? 0)))
|
|
72
|
+
throw new Error("Invalid Astra effective effort");
|
|
73
|
+
parents.set(record.id, record);
|
|
74
|
+
}
|
|
75
|
+
const unknown = entries.some((e) => this.acknowledged.get(e.id) !== JSON.stringify(e));
|
|
76
|
+
const file = this.reader.getSessionFile();
|
|
77
|
+
if (unknown && file && branch.some((e) => e.type === "message" && e.message?.role === "assistant")) {
|
|
78
|
+
const sessionId = this.reader.getSessionId(),
|
|
79
|
+
leaf = this.reader.getLeafId();
|
|
80
|
+
const snapshot = await readOnlySessionSnapshot(file);
|
|
81
|
+
const persisted = activeReadOnlySessionBranch(snapshot, leaf);
|
|
82
|
+
if (
|
|
83
|
+
snapshot.sessionId !== sessionId ||
|
|
84
|
+
this.reader.getLeafId() !== leaf ||
|
|
85
|
+
JSON.stringify(persisted) !== JSON.stringify(branch)
|
|
86
|
+
)
|
|
87
|
+
throw new Error("Astra persisted ancestry differs");
|
|
88
|
+
}
|
|
89
|
+
for (const entry of entries) this.acknowledged.set(entry.id, JSON.stringify(entry));
|
|
90
|
+
return records;
|
|
91
|
+
}
|
|
92
|
+
generation() {
|
|
93
|
+
let generation = "root";
|
|
94
|
+
for (const entry of this.branch()) {
|
|
95
|
+
if (entry.type === "compaction" || entry.type === "branch_summary") generation = entry.id;
|
|
96
|
+
}
|
|
97
|
+
return generation;
|
|
98
|
+
}
|
|
99
|
+
append(record) {
|
|
100
|
+
try {
|
|
101
|
+
if (this.reader.getLeafId() !== record.basis) throw new Error("Astra request ancestry changed");
|
|
102
|
+
this.pi.appendEntry(ENTRY_TYPE, record);
|
|
103
|
+
const entry = this.branch().find(
|
|
104
|
+
(e) => e.type === "custom" && e.customType === ENTRY_TYPE && e.data?.id === record.id,
|
|
105
|
+
);
|
|
106
|
+
if (!entry || entry.parentId !== record.basis || JSON.stringify(entry.data) !== JSON.stringify(record))
|
|
107
|
+
throw new Error("Astra append not acknowledged");
|
|
108
|
+
this.acknowledged.set(entry.id, JSON.stringify(entry));
|
|
109
|
+
} catch (error) {
|
|
110
|
+
this.fault = "Astra append uncertain; native effort retained until session recovery";
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { activeReadOnlySessionBranch, readOnlySessionSnapshot } from "../session-sources/read-only-session.js";
|
|
3
|
+
const ENTRY = "freeflow-request-history-v1";
|
|
4
|
+
const TRANSIENT = new Set([
|
|
5
|
+
"freeflow-runtime-state",
|
|
6
|
+
"freeflow-cognitive-routing-runtime-state",
|
|
7
|
+
"freeflow-routing-v2-state",
|
|
8
|
+
"freeflow-routing-budget",
|
|
9
|
+
"freeflow-routing-communication",
|
|
10
|
+
]);
|
|
11
|
+
const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
12
|
+
function fingerprint(message) {
|
|
13
|
+
const { usage: _usage, timestamp: _timestamp, details: _details, ...body } = message;
|
|
14
|
+
return hash(body);
|
|
15
|
+
}
|
|
16
|
+
function prefixes(messages) {
|
|
17
|
+
const result = [hash([])];
|
|
18
|
+
for (const message of messages) result.push(hash([result.at(-1), fingerprint(message)]));
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
function owned(message) {
|
|
22
|
+
return message?.role === "custom" && TRANSIENT.has(message.customType);
|
|
23
|
+
}
|
|
24
|
+
function parse(value) {
|
|
25
|
+
if (
|
|
26
|
+
!value ||
|
|
27
|
+
value.version !== 1 ||
|
|
28
|
+
typeof value.id !== "string" ||
|
|
29
|
+
typeof value.view !== "string" ||
|
|
30
|
+
typeof value.generation !== "string" ||
|
|
31
|
+
!(value.basis === null || typeof value.basis === "string") ||
|
|
32
|
+
!Number.isSafeInteger(value.length) ||
|
|
33
|
+
value.length < 0 ||
|
|
34
|
+
!/^[a-f0-9]{64}$/.test(value.prefix) ||
|
|
35
|
+
!(value.parent === null || typeof value.parent === "string") ||
|
|
36
|
+
!value.states ||
|
|
37
|
+
typeof value.states !== "object" ||
|
|
38
|
+
Array.isArray(value.states) ||
|
|
39
|
+
!Object.entries(value.states).every(
|
|
40
|
+
([key, val]) => TRANSIENT.has(key) && typeof val === "string" && /^[a-f0-9]{64}$/.test(val),
|
|
41
|
+
) ||
|
|
42
|
+
!Array.isArray(value.retained) ||
|
|
43
|
+
!value.retained.every((x) => typeof x === "string") ||
|
|
44
|
+
!Array.isArray(value.additions) ||
|
|
45
|
+
!value.additions.every((x) => Number.isSafeInteger(x.at) && x.at >= 0 && x.at <= value.length && owned(x.message))
|
|
46
|
+
)
|
|
47
|
+
throw new Error("Invalid Freeflow context history");
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
/** Preserve only Freeflow-generated occurrences. Native content remains owned by Pi and its projectors. */
|
|
51
|
+
export class RequestHistory {
|
|
52
|
+
pi;
|
|
53
|
+
acknowledged = new Map();
|
|
54
|
+
identity;
|
|
55
|
+
fault = false;
|
|
56
|
+
serial = Promise.resolve();
|
|
57
|
+
revision = 0;
|
|
58
|
+
constructor(pi) {
|
|
59
|
+
this.pi = pi;
|
|
60
|
+
}
|
|
61
|
+
reset() {
|
|
62
|
+
this.revision++;
|
|
63
|
+
this.acknowledged.clear();
|
|
64
|
+
this.identity = undefined;
|
|
65
|
+
this.fault = false;
|
|
66
|
+
}
|
|
67
|
+
async assemble(messages, view, ctx, notice) {
|
|
68
|
+
const revision = this.revision;
|
|
69
|
+
const operation = this.serial.then(async () => {
|
|
70
|
+
if (revision !== this.revision) return messages;
|
|
71
|
+
try {
|
|
72
|
+
return await this.prepare(messages, view, ctx, revision, notice);
|
|
73
|
+
} catch {
|
|
74
|
+
try {
|
|
75
|
+
ctx.ui?.setStatus?.("freeflow-cache", "Freeflow context replay unavailable · current view retained");
|
|
76
|
+
} catch {}
|
|
77
|
+
// Keep the already-qualified projected view on failure, never raw hidden history.
|
|
78
|
+
return messages;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
this.serial = operation.catch(() => {});
|
|
82
|
+
return operation;
|
|
83
|
+
}
|
|
84
|
+
async prepare(messages, view, ctx, revision, notice) {
|
|
85
|
+
const reader = ctx.sessionManager;
|
|
86
|
+
if (!reader?.getBranch || !reader.getLeafId || !reader.getSessionId || !this.pi.appendEntry) return messages;
|
|
87
|
+
const identity = `${reader.getSessionId()}:${reader.getSessionFile?.() ?? "memory"}`;
|
|
88
|
+
if (this.identity !== identity) {
|
|
89
|
+
this.acknowledged.clear();
|
|
90
|
+
this.fault = false;
|
|
91
|
+
this.identity = identity;
|
|
92
|
+
}
|
|
93
|
+
if (this.fault) throw new Error("Uncertain Freeflow context append");
|
|
94
|
+
const branch = reader.getBranch(),
|
|
95
|
+
leaf = reader.getLeafId();
|
|
96
|
+
let parent = null,
|
|
97
|
+
generation = "root";
|
|
98
|
+
const ids = new Set();
|
|
99
|
+
for (const entry of branch) {
|
|
100
|
+
if (entry.parentId !== parent || ids.has(entry.id)) throw new Error("Invalid context ancestry");
|
|
101
|
+
parent = entry.id;
|
|
102
|
+
ids.add(entry.id);
|
|
103
|
+
if (entry.type === "compaction" || entry.type === "branch_summary") generation = entry.id;
|
|
104
|
+
}
|
|
105
|
+
if (parent !== leaf) throw new Error("Context leaf changed");
|
|
106
|
+
const entries = branch.filter((e) => e.type === "custom" && e.customType === ENTRY);
|
|
107
|
+
if (
|
|
108
|
+
entries.some((e) => this.acknowledged.get(e.id) !== hash(e)) &&
|
|
109
|
+
reader.getSessionFile?.() &&
|
|
110
|
+
branch.some((e) => e.message?.role === "assistant")
|
|
111
|
+
) {
|
|
112
|
+
const snapshot = await readOnlySessionSnapshot(reader.getSessionFile());
|
|
113
|
+
if (
|
|
114
|
+
snapshot.sessionId !== reader.getSessionId() ||
|
|
115
|
+
JSON.stringify(activeReadOnlySessionBranch(snapshot, leaf)) !== JSON.stringify(branch)
|
|
116
|
+
)
|
|
117
|
+
throw new Error("Context history readback differs");
|
|
118
|
+
}
|
|
119
|
+
if (revision !== this.revision || reader.getLeafId() !== leaf) throw new Error("Context changed while preparing");
|
|
120
|
+
const frames = [],
|
|
121
|
+
byId = new Map();
|
|
122
|
+
for (const entry of entries) {
|
|
123
|
+
const frame = parse(entry.data);
|
|
124
|
+
if (
|
|
125
|
+
(frame.basis !== entry.parentId && !(reader.getHeader?.()?.parentSession && !ids.has(frame.basis))) ||
|
|
126
|
+
byId.has(frame.id)
|
|
127
|
+
)
|
|
128
|
+
throw new Error("Context frame anchor differs");
|
|
129
|
+
const previous = frame.parent ? byId.get(frame.parent) : undefined;
|
|
130
|
+
if (frame.parent && (!previous || previous.generation !== frame.generation || previous.length > frame.length))
|
|
131
|
+
throw new Error("Context frame parent missing");
|
|
132
|
+
frames.push(frame);
|
|
133
|
+
byId.set(frame.id, frame);
|
|
134
|
+
this.acknowledged.set(entry.id, hash(entry));
|
|
135
|
+
}
|
|
136
|
+
const base = messages.filter((m) => !owned(m));
|
|
137
|
+
const current = messages
|
|
138
|
+
.filter(owned)
|
|
139
|
+
.filter((message) => !notice || message.customType !== "freeflow-routing-budget");
|
|
140
|
+
const hashes = prefixes(base);
|
|
141
|
+
const candidates = frames.filter((f) => f.generation === generation && hashes[f.length] === f.prefix);
|
|
142
|
+
const prior = candidates.reduce((best, f) => (!best || f.length >= best.length ? f : best), undefined);
|
|
143
|
+
const states = { ...prior?.states },
|
|
144
|
+
additions = [];
|
|
145
|
+
const seenRetained = new Set(prior?.retained ?? []);
|
|
146
|
+
for (const message of current) {
|
|
147
|
+
const signature = fingerprint(message),
|
|
148
|
+
kind = message.customType;
|
|
149
|
+
if (kind === "freeflow-routing-communication" ? seenRetained.has(signature) : states[kind] === signature)
|
|
150
|
+
continue;
|
|
151
|
+
additions.push({ at: base.length, message: structuredClone(message) });
|
|
152
|
+
if (kind === "freeflow-routing-communication") seenRetained.add(signature);
|
|
153
|
+
else states[kind] = signature;
|
|
154
|
+
}
|
|
155
|
+
const injections = [];
|
|
156
|
+
const chain = [];
|
|
157
|
+
for (let cursor = prior; cursor; cursor = cursor.parent ? byId.get(cursor.parent) : undefined)
|
|
158
|
+
chain.unshift(cursor);
|
|
159
|
+
for (const frame of chain) injections.push(...frame.additions);
|
|
160
|
+
injections.push(...additions);
|
|
161
|
+
const result = [];
|
|
162
|
+
let next = 0;
|
|
163
|
+
for (let i = 0; i <= base.length; i++) {
|
|
164
|
+
while (injections[next]?.at === i) result.push(structuredClone(injections[next++].message));
|
|
165
|
+
if (i < base.length) result.push(base[i]);
|
|
166
|
+
}
|
|
167
|
+
if (next !== injections.length) throw new Error("Context anchor ordering differs");
|
|
168
|
+
if (notice) {
|
|
169
|
+
const warning = notice(result);
|
|
170
|
+
if (warning || states["freeflow-routing-budget"]) {
|
|
171
|
+
const message = warning ?? {
|
|
172
|
+
role: "custom",
|
|
173
|
+
customType: "freeflow-routing-budget",
|
|
174
|
+
display: false,
|
|
175
|
+
content: "Routing budget warning cleared for the current request.",
|
|
176
|
+
timestamp: 0,
|
|
177
|
+
};
|
|
178
|
+
const signature = fingerprint(message);
|
|
179
|
+
if (states[message.customType] !== signature) {
|
|
180
|
+
states[message.customType] = signature;
|
|
181
|
+
additions.push({ at: base.length, message });
|
|
182
|
+
result.push(message);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (!prior || prior.length !== base.length || additions.length) {
|
|
187
|
+
const frame = {
|
|
188
|
+
version: 1,
|
|
189
|
+
id: randomUUID(),
|
|
190
|
+
basis: leaf,
|
|
191
|
+
view,
|
|
192
|
+
generation,
|
|
193
|
+
length: base.length,
|
|
194
|
+
prefix: hashes.at(-1),
|
|
195
|
+
parent: prior?.id ?? null,
|
|
196
|
+
states,
|
|
197
|
+
retained: [...seenRetained],
|
|
198
|
+
additions,
|
|
199
|
+
};
|
|
200
|
+
try {
|
|
201
|
+
this.pi.appendEntry(ENTRY, frame);
|
|
202
|
+
const entry = reader.getBranch().find((e) => e.customType === ENTRY && e.data?.id === frame.id);
|
|
203
|
+
if (!entry || entry.parentId !== leaf || JSON.stringify(entry.data) !== JSON.stringify(frame))
|
|
204
|
+
throw new Error("Context append not acknowledged");
|
|
205
|
+
this.acknowledged.set(entry.id, hash(entry));
|
|
206
|
+
} catch (error) {
|
|
207
|
+
this.fault = true;
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
ctx.ui?.setStatus?.("freeflow-cache", undefined);
|
|
213
|
+
} catch {}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
}
|