@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
package/command-surface.json
CHANGED
|
@@ -86,7 +86,13 @@
|
|
|
86
86
|
"kind": "settings"
|
|
87
87
|
},
|
|
88
88
|
{
|
|
89
|
-
"command": "/freeflow profile <
|
|
89
|
+
"command": "/freeflow profile <coordinator|executor|auto>",
|
|
90
|
+
"handler": "freeflow",
|
|
91
|
+
"kind": "cognitive-routing-control",
|
|
92
|
+
"piOnly": true
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
"command": "/freeflow resume",
|
|
90
96
|
"handler": "freeflow",
|
|
91
97
|
"kind": "cognitive-routing-control",
|
|
92
98
|
"piOnly": true
|
package/gemini-extension.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hassangameryt/freeflow",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Feedback-based control system for coding agents.",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"format": "prettier --write .",
|
|
20
20
|
"format:check": "prettier --check .",
|
|
21
21
|
"format:pi-extension-dist": "prettier --write pi-extension/dist",
|
|
22
|
-
"build:pi-extension": "tsc -p pi-extension/tsconfig.json && npm run format:pi-extension-dist",
|
|
22
|
+
"build:pi-extension": "node -e \"require('node:fs').rmSync('pi-extension/dist', { recursive: true, force: true })\" && tsc -p pi-extension/tsconfig.json && npm run format:pi-extension-dist",
|
|
23
23
|
"build": "npm run build:pi-extension",
|
|
24
24
|
"typecheck": "tsc -p pi-extension/tsconfig.json --noEmit",
|
|
25
25
|
"check": "npm run typecheck && npm run check:source && npm run check:host-manifests && npm run check:changelog && npm run check:release-workflow && npm run check:docs && npm run format:check && npm run check:release-version && npm run check:commands && npm run check:activation && npm run check:runtime && npm run check:package",
|
|
@@ -101,8 +101,8 @@
|
|
|
101
101
|
"@earendil-works/pi-tui": "*"
|
|
102
102
|
},
|
|
103
103
|
"devDependencies": {
|
|
104
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
105
|
-
"@earendil-works/pi-tui": "0.
|
|
104
|
+
"@earendil-works/pi-coding-agent": "0.85.1",
|
|
105
|
+
"@earendil-works/pi-tui": "0.85.1",
|
|
106
106
|
"@types/node": "^22.15.30",
|
|
107
107
|
"prettier": "3.9.5",
|
|
108
108
|
"typescript": "^5.8.3"
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// A local planning estimate, not a provider token count or an output allocation.
|
|
2
|
+
// In particular, base64 and native usage/metadata are not model text.
|
|
3
|
+
export function estimateRequest(systemPrompt, tools, messages, model) {
|
|
4
|
+
const text = (value) => Math.ceil(value.length / 3);
|
|
5
|
+
const content = (value) =>
|
|
6
|
+
typeof value === "string"
|
|
7
|
+
? text(value)
|
|
8
|
+
: Array.isArray(value)
|
|
9
|
+
? value.reduce(
|
|
10
|
+
(sum, b) =>
|
|
11
|
+
sum +
|
|
12
|
+
(b.type === "image"
|
|
13
|
+
? 1200
|
|
14
|
+
: b.type === "toolCall"
|
|
15
|
+
? text(b.name + JSON.stringify(b.arguments ?? {}))
|
|
16
|
+
: b.type === "thinking"
|
|
17
|
+
? text(b.thinking ?? "")
|
|
18
|
+
: text(b.text ?? "")),
|
|
19
|
+
0,
|
|
20
|
+
)
|
|
21
|
+
: 0;
|
|
22
|
+
const estimatedTokens =
|
|
23
|
+
text(systemPrompt) +
|
|
24
|
+
text(JSON.stringify(tools.map((t) => ({ name: t.name, description: t.description, parameters: t.parameters })))) +
|
|
25
|
+
messages.reduce((sum, m) => sum + 8 + content(m.content), 0);
|
|
26
|
+
const window = model?.contextWindow ?? 0;
|
|
27
|
+
const outputReserve = Math.min(4096, Math.max(1, Math.floor(window / 10)));
|
|
28
|
+
const maximumInputTokens = Math.max(0, window - outputReserve);
|
|
29
|
+
const estimateMethod =
|
|
30
|
+
"Planning estimate: text characters / 3, 1200 tokens/image, schemas and message framing; output headroom is not the provider allocation";
|
|
31
|
+
const warnings =
|
|
32
|
+
estimatedTokens > maximumInputTokens
|
|
33
|
+
? [
|
|
34
|
+
{
|
|
35
|
+
ref: "",
|
|
36
|
+
code: "budget_estimate",
|
|
37
|
+
detail: `Estimated input ${estimatedTokens} exceeds planning allowance ${maximumInputTokens}. Actual output allocation and image tokenization are provider-dependent; fit is unconfirmed. Use native compaction or revise explicitly if the provider rejects the request.`,
|
|
38
|
+
},
|
|
39
|
+
]
|
|
40
|
+
: [];
|
|
41
|
+
return { estimatedTokens, maximumInputTokens, outputReserve, estimateMethod, warnings };
|
|
42
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { DELEGATION_MODES, EFFORTS, PROFILES, canonical, isObject, workersForDelegation } from "./types.js";
|
|
2
|
+
export const supportsCognitiveRoutingModelRegistry = (host) =>
|
|
3
|
+
typeof host?.modelRegistry?.find === "function" && typeof host?.modelRegistry?.getApiKeyAndHeaders === "function";
|
|
4
|
+
export const pairFromProfile = (profile) => ({
|
|
5
|
+
provider: profile.provider,
|
|
6
|
+
modelId: profile.model,
|
|
7
|
+
thinking: profile.thinking,
|
|
8
|
+
});
|
|
9
|
+
function parseLayer(raw) {
|
|
10
|
+
if (raw === undefined) return {};
|
|
11
|
+
if (
|
|
12
|
+
!isObject(raw) ||
|
|
13
|
+
Object.keys(raw).some((key) => !["enabled", "delegation", "projection", "profiles"].includes(key))
|
|
14
|
+
)
|
|
15
|
+
throw new Error(
|
|
16
|
+
"Routing requires the enabled/delegation/projection/profiles schema; experimental legacy configuration is not migrated.",
|
|
17
|
+
);
|
|
18
|
+
for (const key of ["enabled", "projection"])
|
|
19
|
+
if (raw[key] !== undefined && typeof raw[key] !== "boolean") throw new Error(`${key} must be boolean.`);
|
|
20
|
+
if (raw.delegation !== undefined && !DELEGATION_MODES.includes(raw.delegation))
|
|
21
|
+
throw new Error("delegation must be executor, helper, or both.");
|
|
22
|
+
if (raw.profiles !== undefined) {
|
|
23
|
+
if (!isObject(raw.profiles) || Object.keys(raw.profiles).some((key) => !PROFILES.includes(key)))
|
|
24
|
+
throw new Error("Profiles must be coordinator, helper, or executor.");
|
|
25
|
+
for (const profile of Object.values(raw.profiles)) {
|
|
26
|
+
if (
|
|
27
|
+
!isObject(profile) ||
|
|
28
|
+
Object.keys(profile).some((key) => !["provider", "model", "thinking"].includes(key)) ||
|
|
29
|
+
typeof profile.provider !== "string" ||
|
|
30
|
+
!profile.provider.trim() ||
|
|
31
|
+
typeof profile.model !== "string" ||
|
|
32
|
+
!profile.model.trim() ||
|
|
33
|
+
!EFFORTS.includes(profile.thinking)
|
|
34
|
+
)
|
|
35
|
+
throw new Error("Each profile requires provider, model, and supported thinking.");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return raw;
|
|
39
|
+
}
|
|
40
|
+
export async function resolveCognitiveRoutingState(repository, personal, ctx) {
|
|
41
|
+
const state = {
|
|
42
|
+
configured: repository?.cognitiveRouting !== undefined || personal?.cognitiveRouting !== undefined,
|
|
43
|
+
configValid: true,
|
|
44
|
+
enabled: false,
|
|
45
|
+
effective: false,
|
|
46
|
+
enabledSource: "default",
|
|
47
|
+
delegation: "executor",
|
|
48
|
+
delegationSource: "default",
|
|
49
|
+
projection: false,
|
|
50
|
+
projectionSource: "default",
|
|
51
|
+
profiles: {},
|
|
52
|
+
profileSources: {},
|
|
53
|
+
blockingReason: { code: "disabled", message: "Cognitive Routing is disabled." },
|
|
54
|
+
};
|
|
55
|
+
try {
|
|
56
|
+
for (const [source, raw] of [
|
|
57
|
+
["repository", repository?.cognitiveRouting],
|
|
58
|
+
["personal", personal?.cognitiveRouting],
|
|
59
|
+
]) {
|
|
60
|
+
const layer = parseLayer(raw);
|
|
61
|
+
if (layer.enabled !== undefined) {
|
|
62
|
+
state.enabled = layer.enabled;
|
|
63
|
+
state.enabledSource = source;
|
|
64
|
+
}
|
|
65
|
+
if (layer.delegation !== undefined) {
|
|
66
|
+
state.delegation = layer.delegation;
|
|
67
|
+
state.delegationSource = source;
|
|
68
|
+
}
|
|
69
|
+
if (layer.projection !== undefined) {
|
|
70
|
+
state.projection = layer.projection;
|
|
71
|
+
state.projectionSource = source;
|
|
72
|
+
}
|
|
73
|
+
for (const profile of PROFILES)
|
|
74
|
+
if (layer.profiles?.[profile]) {
|
|
75
|
+
state.profiles[profile] = layer.profiles[profile];
|
|
76
|
+
state.profileSources[profile] = source;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
} catch (error) {
|
|
80
|
+
return {
|
|
81
|
+
...state,
|
|
82
|
+
configValid: false,
|
|
83
|
+
blockingReason: { code: "config_invalid", message: error instanceof Error ? error.message : String(error) },
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
if (!state.enabled) return state;
|
|
87
|
+
if (!supportsCognitiveRoutingModelRegistry(ctx))
|
|
88
|
+
return {
|
|
89
|
+
...state,
|
|
90
|
+
blockingReason: { code: "host_unsupported", message: "Required public Pi model registry is unavailable." },
|
|
91
|
+
};
|
|
92
|
+
const requiredProfiles = ["coordinator", ...workersForDelegation(state.delegation)];
|
|
93
|
+
for (const name of requiredProfiles) {
|
|
94
|
+
const profile = state.profiles[name];
|
|
95
|
+
if (!profile)
|
|
96
|
+
return { ...state, blockingReason: { code: "profile_missing", message: `Configure the ${name} profile.` } };
|
|
97
|
+
const model = ctx.modelRegistry.find(profile.provider, profile.model);
|
|
98
|
+
if (!model)
|
|
99
|
+
return { ...state, blockingReason: { code: "profile_unavailable", message: `Model unavailable for ${name}.` } };
|
|
100
|
+
const clamp = ctx.modelRegistry.clampThinkingLevel?.bind(ctx.modelRegistry);
|
|
101
|
+
const supported = !model.reasoning
|
|
102
|
+
? profile.thinking === "off"
|
|
103
|
+
: clamp
|
|
104
|
+
? clamp(model, profile.thinking) === profile.thinking
|
|
105
|
+
: model.thinkingLevelMap?.[profile.thinking] !== null &&
|
|
106
|
+
(!["xhigh", "max"].includes(profile.thinking) || model.thinkingLevelMap?.[profile.thinking] !== undefined);
|
|
107
|
+
if (!supported)
|
|
108
|
+
return {
|
|
109
|
+
...state,
|
|
110
|
+
blockingReason: { code: "profile_clamped", message: `Requested ${name} effort is not supported exactly.` },
|
|
111
|
+
};
|
|
112
|
+
try {
|
|
113
|
+
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
114
|
+
if (!auth?.ok)
|
|
115
|
+
return {
|
|
116
|
+
...state,
|
|
117
|
+
blockingReason: { code: "profile_unauthenticated", message: `Authentication unavailable for ${name}.` },
|
|
118
|
+
};
|
|
119
|
+
} catch {
|
|
120
|
+
return {
|
|
121
|
+
...state,
|
|
122
|
+
blockingReason: { code: "profile_unauthenticated", message: `Authentication resolution failed for ${name}.` },
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const worker of workersForDelegation(state.delegation))
|
|
127
|
+
if (canonical(state.profiles.coordinator) === canonical(state.profiles[worker]))
|
|
128
|
+
return {
|
|
129
|
+
...state,
|
|
130
|
+
blockingReason: {
|
|
131
|
+
code: "profiles_identical",
|
|
132
|
+
message: `Configure distinct Coordinator and ${worker} model/effort pairs.`,
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
return { ...state, effective: true, blockingReason: { code: "", message: "" } };
|
|
136
|
+
}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { annotateSources } from "../session-sources/provenance.js";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { textRef } from "../session-sources/sources.js";
|
|
4
|
+
import { canonical, emptySelection, isWorkerProfile, requireCondition as check } from "./types.js";
|
|
5
|
+
import { estimateRequest } from "./budget.js";
|
|
6
|
+
export function changeSelection(prior, input, sources, state) {
|
|
7
|
+
check(
|
|
8
|
+
Array.isArray(input.refs) &&
|
|
9
|
+
input.refs.length <= 64 &&
|
|
10
|
+
input.refs.every((r) => typeof r === "string" && r.length <= 512),
|
|
11
|
+
"invalid_refs",
|
|
12
|
+
);
|
|
13
|
+
if (input.operation === "remove")
|
|
14
|
+
check(
|
|
15
|
+
typeof input.reason === "string" && input.reason.trim() && input.reason.length <= 2048,
|
|
16
|
+
"withdrawal_reason_required",
|
|
17
|
+
);
|
|
18
|
+
const next = structuredClone(prior);
|
|
19
|
+
for (const ref of new Set(input.refs)) {
|
|
20
|
+
const existed = next.selected.includes(ref) || next.unresolved.some((p) => p.ref === ref);
|
|
21
|
+
if (input.operation === "remove") {
|
|
22
|
+
next.unresolved = next.unresolved.filter((p) => p.ref !== ref);
|
|
23
|
+
next.selected = next.selected.filter((r) => r !== ref);
|
|
24
|
+
if (existed) next.withdrawals.push({ ref, reason: input.reason });
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const problem = prior.selected.includes(ref) ? sources.eligible(ref, state) : sources.selectionProblem(ref, state);
|
|
28
|
+
const index = next.unresolved.findIndex((p) => p.ref === ref);
|
|
29
|
+
if (problem) {
|
|
30
|
+
if (index < 0) next.unresolved.push(problem);
|
|
31
|
+
else next.unresolved[index] = problem;
|
|
32
|
+
} else {
|
|
33
|
+
if (index >= 0) next.unresolved.splice(index, 1);
|
|
34
|
+
if (!next.selected.includes(ref)) next.selected.push(ref);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (canonical(next) === canonical(prior)) return prior;
|
|
38
|
+
next.revision++;
|
|
39
|
+
return next;
|
|
40
|
+
}
|
|
41
|
+
export function representationProblems(source, model, structural = false) {
|
|
42
|
+
const message = source.original?.message ?? source.message,
|
|
43
|
+
content = Array.isArray(source.message.content) ? source.message.content : [];
|
|
44
|
+
if (message.role === "assistant" && ["error", "aborted"].includes(message.stopReason))
|
|
45
|
+
return [
|
|
46
|
+
{
|
|
47
|
+
ref: source.ref,
|
|
48
|
+
code: "target_representation",
|
|
49
|
+
detail:
|
|
50
|
+
"Native compatibility conversion may omit failed/aborted assistant output; exact delivery is not promised.",
|
|
51
|
+
},
|
|
52
|
+
];
|
|
53
|
+
if (content.some((b) => b.type === "image") && !model?.input?.includes("image"))
|
|
54
|
+
return [
|
|
55
|
+
{ ref: source.ref, code: "target_representation", detail: "The receiving model does not support image input." },
|
|
56
|
+
];
|
|
57
|
+
if (
|
|
58
|
+
!structural &&
|
|
59
|
+
!source.original &&
|
|
60
|
+
content.some((b) => b.type === "thinking" && (b.redacted || b.thinkingSignature)) &&
|
|
61
|
+
(message.provider !== model?.provider || message.model !== model?.id || message.api !== model?.api)
|
|
62
|
+
)
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
ref: source.ref,
|
|
66
|
+
code: "target_representation",
|
|
67
|
+
detail: `Whole native signed content is not qualified across this model boundary. Inspect the explicit assistant-text source ${textRef(source.ref)} when visible text is the intended evidence.`,
|
|
68
|
+
},
|
|
69
|
+
];
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
export function prepareView(options) {
|
|
73
|
+
const { sources, state } = options;
|
|
74
|
+
const associated = sources.associate(options.messages);
|
|
75
|
+
const selective = options.projection && options.view === "coordinator";
|
|
76
|
+
const assessment = state.assessment;
|
|
77
|
+
const attention = selective && assessment?.view === "suspended" && !options.restoring && !options.preparingReturn;
|
|
78
|
+
const handoffId = options.preparingReturn ?? (!attention ? assessment?.handoffId : undefined);
|
|
79
|
+
const handoff = handoffId ? state.handoffs.get(handoffId) : undefined;
|
|
80
|
+
const assignmentId = handoff?.assignmentId ?? state.assignmentId;
|
|
81
|
+
const current = assignmentId ? (state.selections.get(assignmentId) ?? emptySelection()) : emptySelection();
|
|
82
|
+
const required = new Set(selective && !attention && assignmentId ? current.selected : []);
|
|
83
|
+
const promised = handoff && state.reservations.get(handoff.id);
|
|
84
|
+
const admitted = new Set();
|
|
85
|
+
if (selective)
|
|
86
|
+
for (const selection of state.selections.values()) for (const ref of selection.selected) admitted.add(ref);
|
|
87
|
+
// Accepted return receipts are communication, independent of selected task evidence.
|
|
88
|
+
// Their ordinary active occurrence survives closure; compaction still owns its lifetime.
|
|
89
|
+
const full = new Map();
|
|
90
|
+
const structural = new Map();
|
|
91
|
+
const problems = selective && !attention && assignmentId ? [...current.unresolved] : [];
|
|
92
|
+
for (const item of associated) {
|
|
93
|
+
if (!item.source) continue;
|
|
94
|
+
if (
|
|
95
|
+
!selective ||
|
|
96
|
+
!isWorkerProfile(item.source.producer) ||
|
|
97
|
+
admitted.has(item.source.ref) ||
|
|
98
|
+
(item.source.reportHandoff && state.handoffs.has(item.source.reportHandoff))
|
|
99
|
+
)
|
|
100
|
+
full.set(item.source.ref, item.source);
|
|
101
|
+
const visible = sources.byRef.get(textRef(item.source.ref));
|
|
102
|
+
if (selective && visible && admitted.has(visible.ref)) full.set(visible.ref, visible);
|
|
103
|
+
}
|
|
104
|
+
for (const ref of required) {
|
|
105
|
+
if (sources.ambiguous.has(ref)) {
|
|
106
|
+
problems.push({
|
|
107
|
+
ref,
|
|
108
|
+
code: "ambiguous_occurrence",
|
|
109
|
+
detail: "The active representation cannot be associated with one canonical occurrence.",
|
|
110
|
+
});
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const source = sources.byRef.get(ref),
|
|
114
|
+
error = sources.eligible(ref, state);
|
|
115
|
+
if (error) {
|
|
116
|
+
problems.push(error);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const expected =
|
|
120
|
+
promised && promised.selectionRevision === current.revision
|
|
121
|
+
? promised.sources.find((s) => s.ref === ref)
|
|
122
|
+
: undefined;
|
|
123
|
+
if (expected && expected.bodyHash !== source.hash) {
|
|
124
|
+
problems.push({
|
|
125
|
+
ref,
|
|
126
|
+
code: "source_changed",
|
|
127
|
+
detail: "The captured source differs from the prepared reservation.",
|
|
128
|
+
});
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
full.set(ref, source);
|
|
132
|
+
}
|
|
133
|
+
// A selected result carries its complete native call group; siblings may be structural only.
|
|
134
|
+
for (const source of full.values()) {
|
|
135
|
+
const exchange = sources.exchange(source);
|
|
136
|
+
if (required.has(source.ref)) problems.push(...exchange.problems, ...representationProblems(source, options.model));
|
|
137
|
+
for (const sibling of exchange.sources) if (!full.has(sibling.ref)) structural.set(sibling.ref, sibling);
|
|
138
|
+
}
|
|
139
|
+
for (const source of structural.values())
|
|
140
|
+
if (source.message.role === "assistant" && required.size)
|
|
141
|
+
problems.push(...representationProblems(source, options.model, true));
|
|
142
|
+
const render = (source) => {
|
|
143
|
+
const message = structuredClone(source.message);
|
|
144
|
+
if (source.message.role === "assistant" && !full.has(source.ref) && full.has(textRef(source.ref)))
|
|
145
|
+
message.content = message.content.filter((b) => b.type !== "text");
|
|
146
|
+
if (full.has(source.ref) || source.message.role !== "toolResult") return message;
|
|
147
|
+
return {
|
|
148
|
+
...structuredClone(source.message),
|
|
149
|
+
content: [{ type: "text", text: "[Worker result omitted from this view]" }],
|
|
150
|
+
details: undefined,
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
// Insert resolved historical occurrences before the first later native occurrence, retaining
|
|
154
|
+
// opaque/common messages in their original order rather than moving user input wholesale.
|
|
155
|
+
const ordered = sources.ordered(new Map([...structural, ...full]).values());
|
|
156
|
+
const rank = new Map(options.sources.entries.map((entry, index) => [entry.id, index]));
|
|
157
|
+
const activeRefs = new Set(associated.flatMap((i) => (i.source ? [i.source.ref] : [])));
|
|
158
|
+
const historical = ordered.filter((s) => !activeRefs.has(s.ref));
|
|
159
|
+
const emitted = new Set();
|
|
160
|
+
let messages = [];
|
|
161
|
+
const renderedSources = new Map();
|
|
162
|
+
let cursor = 0;
|
|
163
|
+
const emit = (source) => {
|
|
164
|
+
if (source.original && full.has(source.original.ref)) return;
|
|
165
|
+
if (!emitted.has(source.ref)) {
|
|
166
|
+
const message = render(source);
|
|
167
|
+
messages.push(message);
|
|
168
|
+
renderedSources.set(message, source);
|
|
169
|
+
emitted.add(source.ref);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
for (const item of associated) {
|
|
173
|
+
if (item.source) {
|
|
174
|
+
while (
|
|
175
|
+
cursor < historical.length &&
|
|
176
|
+
(rank.get(historical[cursor].entry.id) ?? 0) < (rank.get(item.source.entry.id) ?? 0)
|
|
177
|
+
)
|
|
178
|
+
emit(historical[cursor++]);
|
|
179
|
+
const visible = full.get(textRef(item.source.ref));
|
|
180
|
+
if (visible) emit(visible);
|
|
181
|
+
if (full.has(item.source.ref) || structural.has(item.source.ref)) emit(item.source);
|
|
182
|
+
} else messages.push(item.message);
|
|
183
|
+
}
|
|
184
|
+
while (cursor < historical.length) emit(historical[cursor++]);
|
|
185
|
+
const fullSources = [...full.values()];
|
|
186
|
+
messages = annotateSources(messages, renderedSources, new Set(full.keys()), sources, options.instance);
|
|
187
|
+
// Restore exact current communication only when its accepted occurrence is absent.
|
|
188
|
+
const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
189
|
+
const baseReport = assessment
|
|
190
|
+
? state.handoffs.get(assessment.handoffId)
|
|
191
|
+
: handoff?.kind === "return"
|
|
192
|
+
? handoff
|
|
193
|
+
: undefined;
|
|
194
|
+
const recovery = state.recoveryId
|
|
195
|
+
? state.recoveries.get(state.recoveryId)
|
|
196
|
+
: [...state.recoveries.values()]
|
|
197
|
+
.reverse()
|
|
198
|
+
.find(
|
|
199
|
+
(candidate) => candidate.assessmentHandoffId === assessment?.handoffId && candidate.state === "completed",
|
|
200
|
+
);
|
|
201
|
+
const recoveryRequest = recovery ? state.handoffs.get(recovery.requestHandoffId) : undefined;
|
|
202
|
+
const supplement =
|
|
203
|
+
handoff?.kind === "recovery-return"
|
|
204
|
+
? handoff
|
|
205
|
+
: recovery?.supplementHandoffId
|
|
206
|
+
? state.handoffs.get(recovery.supplementHandoffId)
|
|
207
|
+
: undefined;
|
|
208
|
+
const hasCommunication = (h, field, value, metadata = {}) =>
|
|
209
|
+
messages.some((m) => {
|
|
210
|
+
const matches = (payload) =>
|
|
211
|
+
payload?.[field] === value &&
|
|
212
|
+
Object.entries(metadata).every(([key, expected]) => canonical(payload?.[key]) === canonical(expected));
|
|
213
|
+
if (m.role === "assistant")
|
|
214
|
+
return m.content?.some((b) => b.type === "toolCall" && b.id === h.toolCallId && matches(b.arguments));
|
|
215
|
+
if (m.role !== "toolResult" || m.toolCallId !== h.toolCallId) return false;
|
|
216
|
+
return m.content?.some((b) => {
|
|
217
|
+
if (b.type !== "text") return false;
|
|
218
|
+
try {
|
|
219
|
+
return matches(JSON.parse(b.text));
|
|
220
|
+
} catch {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
const restore = (kind, id, body) =>
|
|
226
|
+
messages.push({
|
|
227
|
+
role: "custom",
|
|
228
|
+
customType: "freeflow-routing-communication",
|
|
229
|
+
display: false,
|
|
230
|
+
content: `${kind} ${id}:\n${body}`,
|
|
231
|
+
timestamp: 0,
|
|
232
|
+
details: { routingInstance: options.instance },
|
|
233
|
+
});
|
|
234
|
+
if (a) {
|
|
235
|
+
const accepted = state.handoffs.get(a.delegateHandoffId);
|
|
236
|
+
if (accepted && !hasCommunication(accepted, "contract", a.contract))
|
|
237
|
+
restore("Current exact assignment", a.id, a.contract);
|
|
238
|
+
}
|
|
239
|
+
if (baseReport) {
|
|
240
|
+
const metadata = { outcome: baseReport.outcome, limitations: baseReport.limitations };
|
|
241
|
+
const hasBody = hasCommunication(baseReport, "report", baseReport.text);
|
|
242
|
+
// Tool arguments establish accepted content but do not carry harness-assigned
|
|
243
|
+
// revision/lineage. Old receipts and partially retained calls need metadata too.
|
|
244
|
+
const complete = hasCommunication(baseReport, "report", baseReport.text, {
|
|
245
|
+
...metadata,
|
|
246
|
+
reportRevision: baseReport.reportRevision,
|
|
247
|
+
assignmentRef: `assignment:${baseReport.assignmentId}`,
|
|
248
|
+
reportRef: `report:${baseReport.id}:${baseReport.reportRevision}`,
|
|
249
|
+
});
|
|
250
|
+
if (!complete)
|
|
251
|
+
restore(
|
|
252
|
+
"Saved report",
|
|
253
|
+
baseReport.id,
|
|
254
|
+
`Producer: ${baseReport.from}\nAssignment: assignment:${baseReport.assignmentId}\nReport ref: report:${baseReport.id}:${baseReport.reportRevision}\nRevision: ${baseReport.reportRevision}\nOutcome: ${baseReport.outcome}\nLimitations: ${JSON.stringify(baseReport.limitations)}${hasBody ? "\nReport text is present in its accepted native occurrence above." : `\nReport:\n${baseReport.text}`}`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
if (recovery && recoveryRequest && !hasCommunication(recoveryRequest, "request", recovery.request))
|
|
258
|
+
restore(
|
|
259
|
+
"Recovery request",
|
|
260
|
+
recovery.id,
|
|
261
|
+
`Assignment: assignment:${recovery.assignmentId}\nParent report: report:${recovery.assessmentHandoffId}:${recovery.baseReportRevision}\nAllowed paths: ${JSON.stringify(recovery.paths)}\nRequest:\n${recovery.request}`,
|
|
262
|
+
);
|
|
263
|
+
if (recovery && supplement) {
|
|
264
|
+
const hasBody = hasCommunication(supplement, "report", supplement.text);
|
|
265
|
+
const complete = hasCommunication(supplement, "report", supplement.text, {
|
|
266
|
+
outcome: supplement.outcome,
|
|
267
|
+
limitations: supplement.limitations,
|
|
268
|
+
});
|
|
269
|
+
if (!complete)
|
|
270
|
+
restore(
|
|
271
|
+
"Recovery supplement",
|
|
272
|
+
recovery.id,
|
|
273
|
+
`Assignment: assignment:${recovery.assignmentId}\nParent report: report:${recovery.assessmentHandoffId}:${recovery.baseReportRevision}\nSupplement revision: ${supplement.reportRevision}\nOutcome: ${supplement.outcome}\nLimitations: ${JSON.stringify(supplement.limitations)}${hasBody ? "\nSupplement text is present in its accepted native occurrence above." : `\nSupplement:\n${supplement.text}`}`,
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
messages.push(options.runtimeMessage);
|
|
277
|
+
const { estimatedTokens, maximumInputTokens, outputReserve, estimateMethod, warnings } = estimateRequest(
|
|
278
|
+
options.systemPrompt,
|
|
279
|
+
options.tools,
|
|
280
|
+
messages,
|
|
281
|
+
options.model,
|
|
282
|
+
);
|
|
283
|
+
if (warnings.length)
|
|
284
|
+
messages.push({
|
|
285
|
+
role: "custom",
|
|
286
|
+
customType: "freeflow-routing-budget",
|
|
287
|
+
display: false,
|
|
288
|
+
content: warnings.map((w) => w.detail).join("\n"),
|
|
289
|
+
timestamp: 0,
|
|
290
|
+
details: { routingInstance: options.instance },
|
|
291
|
+
});
|
|
292
|
+
if (!options.model?.contextWindow)
|
|
293
|
+
problems.push({ ref: "", code: "delivery_budget", detail: "Receiving model context capacity is unavailable." });
|
|
294
|
+
const reservation =
|
|
295
|
+
handoff && selective
|
|
296
|
+
? {
|
|
297
|
+
id: randomUUID(),
|
|
298
|
+
selectionRevision: current.revision,
|
|
299
|
+
receiver: "coordinator",
|
|
300
|
+
target: options.pair,
|
|
301
|
+
qualification: `native-structural:${options.model?.api ?? "unknown"}; serialized receipt unobserved`,
|
|
302
|
+
sources: [...required].flatMap((ref) => {
|
|
303
|
+
const source = sources.byRef.get(ref);
|
|
304
|
+
return source ? [{ ref, bodyHash: source.hash }] : [];
|
|
305
|
+
}),
|
|
306
|
+
maximumInputTokens,
|
|
307
|
+
outputReserve,
|
|
308
|
+
estimateMethod,
|
|
309
|
+
}
|
|
310
|
+
: undefined;
|
|
311
|
+
return {
|
|
312
|
+
warnings,
|
|
313
|
+
ready: problems.length === 0,
|
|
314
|
+
// Recorded usage describes a prior provider view, which may belong to the
|
|
315
|
+
// other profile. Pi must estimate this assembled view when allocating output.
|
|
316
|
+
// Normalize request metadata only; canonical usage/billing records stay intact.
|
|
317
|
+
messages: messages.map((message) => ({
|
|
318
|
+
...message,
|
|
319
|
+
timestamp: Number.isFinite(message.timestamp) ? message.timestamp : 0,
|
|
320
|
+
...(message.role === "assistant"
|
|
321
|
+
? { usage: { ...message.usage, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 } }
|
|
322
|
+
: {}),
|
|
323
|
+
})),
|
|
324
|
+
problems,
|
|
325
|
+
fullSources,
|
|
326
|
+
reservation,
|
|
327
|
+
estimatedTokens,
|
|
328
|
+
estimateMethod,
|
|
329
|
+
};
|
|
330
|
+
}
|