@hassangameryt/freeflow 0.7.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.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/NOTICE +14 -0
- package/README.md +26 -31
- package/capabilities/cognitive-routing/SKILL.md +106 -161
- package/capabilities/cognitive-routing/references/both-mode.md +36 -0
- package/capabilities/cognitive-routing/references/executor-mode.md +48 -0
- package/capabilities/cognitive-routing/references/helper-mode.md +47 -0
- package/capabilities/compaction/SKILL.md +49 -0
- package/capabilities/compaction/references/summary-format.md +239 -0
- package/command-surface.json +4 -0
- package/gemini-extension.json +1 -1
- package/hooks/shared/runtime-context.mjs +28 -30
- package/licenses/Apache-2.0.txt +55 -0
- package/package.json +22 -9
- package/pi-extension/README.md +41 -0
- package/pi-extension/dist/cognitive-routing/assembler.js +393 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/config.js +5 -2
- package/pi-extension/dist/cognitive-routing/economics.js +45 -0
- package/pi-extension/dist/cognitive-routing/event-schema.js +388 -0
- package/pi-extension/dist/{session-sources/events.js → cognitive-routing/event-store.js} +103 -40
- package/pi-extension/dist/cognitive-routing/gate.js +241 -0
- package/pi-extension/dist/cognitive-routing/handlers.js +899 -0
- package/pi-extension/dist/cognitive-routing/handoffs.js +350 -0
- package/pi-extension/dist/cognitive-routing/model-control.js +467 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/projection.js +229 -56
- package/pi-extension/dist/cognitive-routing/provenance.js +81 -0
- package/pi-extension/dist/cognitive-routing/runtime.js +396 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/schemas.js +43 -7
- package/pi-extension/dist/cognitive-routing/session.js +221 -0
- package/pi-extension/dist/{session-sources → cognitive-routing}/sources.js +99 -85
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/state.js +37 -378
- package/pi-extension/dist/cognitive-routing/status.js +80 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/tools.js +12 -12
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +5 -11
- package/pi-extension/dist/compaction/carry.js +191 -0
- package/pi-extension/dist/compaction/config.js +22 -0
- package/pi-extension/dist/compaction/controller.js +471 -0
- package/pi-extension/dist/compaction/harness.js +77 -0
- package/pi-extension/dist/compaction/results.js +158 -0
- package/pi-extension/dist/compaction/thresholds.js +35 -0
- package/pi-extension/dist/compaction/tool.js +57 -0
- package/pi-extension/dist/host/branch.js +13 -0
- package/pi-extension/dist/host/canonical.js +12 -0
- package/pi-extension/dist/host/catalog.js +77 -0
- package/pi-extension/dist/host/config.js +374 -0
- package/pi-extension/dist/host/projection-tags.js +60 -0
- package/pi-extension/dist/host/prompts.js +82 -0
- package/pi-extension/dist/{session-sources → host}/read-only-session.js +112 -1
- package/pi-extension/dist/{runtime → host}/request-history.js +121 -39
- package/pi-extension/dist/host/runtime-state.js +189 -0
- package/pi-extension/dist/{settings/settings-ui.js → host/settings/freeflow-command.js} +620 -410
- package/pi-extension/dist/{settings/settings-tui.js → host/settings/settings-view.js} +186 -73
- package/pi-extension/dist/host/staging.js +28 -0
- package/pi-extension/dist/host/status.js +101 -0
- package/pi-extension/dist/index.js +423 -173
- package/pi-extension/dist/provider-support/cache/anchor.js +21 -0
- package/pi-extension/dist/provider-support/cache/anthropic.js +102 -0
- package/pi-extension/dist/provider-support/cache/health.js +73 -0
- package/pi-extension/dist/provider-support/cache/index.js +58 -0
- package/pi-extension/dist/provider-support/cache/keepalive.js +210 -0
- package/pi-extension/dist/provider-support/cache/monitor.js +17 -0
- package/pi-extension/dist/provider-support/cache/openai-responses.js +48 -0
- package/pi-extension/dist/provider-support/effort.js +13 -0
- package/pi-extension/dist/provider-support/index.js +44 -3
- package/pi-extension/dist/provider-support/{astra → openai}/adapter.js +46 -29
- package/pi-extension/dist/provider-support/{astra → openai}/history.js +10 -8
- package/pi-extension/dist/provider-support/{astra → openai}/index.js +8 -4
- package/pi-extension/dist/provider-support/{astra → openai}/session-state.js +29 -38
- package/pi-extension/dist/provider-support/routes.js +17 -0
- package/pi-extension/dist/tool-execution/apply-patch/grammar.js +23 -0
- package/pi-extension/dist/tool-execution/apply-patch/match.js +38 -0
- package/pi-extension/dist/tool-execution/apply-patch/parser.js +177 -0
- package/pi-extension/dist/tool-execution/apply-patch/plan.js +201 -0
- package/pi-extension/dist/tool-execution/apply-patch/tool.js +84 -0
- package/pi-extension/dist/tool-execution/background.js +238 -0
- package/pi-extension/dist/tool-execution/bash-guard.js +23 -0
- package/pi-extension/dist/tool-execution/config.js +22 -0
- package/pi-extension/dist/tool-execution/edit-messages.js +120 -0
- package/pi-extension/dist/tool-execution/file-state.js +138 -0
- package/pi-extension/dist/tool-execution/file-tracking.js +143 -0
- package/pi-extension/dist/tool-execution/prompt.js +54 -0
- package/pi-extension/dist/tool-execution/tools.js +16 -0
- package/pi-extension/freeflow/README.md +9 -0
- package/plugin.json +1 -1
- package/runtime/prompts/cognitive-routing.md +4 -4
- package/runtime/prompts/core.md +22 -75
- package/runtime/prompts/interaction-contract.md +15 -8
- package/runtime/prompts/tool-execution.md +38 -0
- package/runtime/prompts/working-method.md +108 -0
- package/skills/action-selection/SKILL.md +39 -47
- package/skills/action-selection/references/trajectory-stalls.md +2 -0
- package/skills/bypass/SKILL.md +2 -2
- package/skills/commit-work/SKILL.md +31 -83
- package/skills/commit-work/references/git-state-edges.md +1 -1
- package/skills/commit-work/references/simple-push.md +2 -0
- package/skills/commit-work/references/staging-decisions.md +1 -1
- package/skills/decision-gate/SKILL.md +31 -50
- package/skills/design-for-depth/SKILL.md +44 -53
- package/skills/design-for-depth/references/design-pressure-signals.md +46 -144
- package/skills/design-for-depth/references/implementation-decisions.md +1 -1
- package/skills/design-for-depth/references/interface-design-loop.md +5 -36
- package/skills/design-for-depth/references/module-and-dependency-design.md +2 -32
- package/skills/design-for-depth/references/state-and-failure-boundaries.md +2 -13
- package/skills/diagnose-failure/SKILL.md +39 -24
- package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +2 -0
- package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +2 -2
- package/skills/discuss/SKILL.md +35 -11
- package/skills/discuss/references/discussion-continuity.md +7 -27
- package/skills/evaluate-skill/SKILL.md +49 -80
- package/skills/evaluate-skill/references/evaluation-definition-schema.md +35 -5
- package/skills/evaluate-skill/references/evaluation-design.md +14 -14
- package/skills/evaluate-skill/references/execution-and-evidence.md +26 -5
- package/skills/evaluate-skill/references/review-and-revision.md +3 -1
- package/skills/evaluate-skill/scripts/lib/definitions.mjs +49 -8
- package/skills/evaluate-skill/scripts/lib/pi.mjs +14 -7
- package/skills/evaluate-skill/scripts/lib/review.mjs +196 -0
- package/skills/evaluate-skill/scripts/lib/runner.mjs +45 -8
- package/skills/evaluate-skill/scripts/lib/sandbox.mjs +2 -0
- package/skills/evaluate-skill/scripts/lib/trials.mjs +103 -0
- package/skills/evaluate-skill/scripts/lib/view.mjs +67 -1
- package/skills/evaluate-skill/scripts/pi-command-tool.mjs +144 -0
- package/skills/evaluate-skill/scripts/pi-guard.mjs +30 -13
- package/skills/evaluate-skill/scripts/skill-eval.mjs +114 -34
- package/skills/execute-work/SKILL.md +41 -9
- package/skills/execute-work/references/code-practices.md +2 -0
- package/skills/execute-work/references/execute-work-edges.md +11 -1
- package/skills/handoff/SKILL.md +1 -1
- package/skills/handoff/references/handoff-templates.md +1 -1
- package/skills/review-artifact/SKILL.md +42 -41
- package/skills/review-artifact/references/adjudicate-artifact-review.md +1 -1
- package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
- package/skills/review-work/SKILL.md +38 -32
- package/skills/review-work/references/adjudicate-work-review.md +1 -1
- package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
- package/skills/review-work/references/security-risk-lens.md +2 -4
- package/skills/setup-freeflow/SKILL.md +3 -1
- package/skills/setup-freeflow/references/activation-contract.md +7 -13
- package/skills/setup-freeflow/references/host-setup.md +3 -3
- package/skills/track-work/SKILL.md +113 -161
- package/skills/track-work/references/working-record-format.md +189 -350
- package/skills/track-work/scripts/lib/document.mjs +62 -6
- package/skills/track-work/scripts/lib/format.mjs +16 -1
- package/skills/track-work/scripts/lib/store.mjs +9 -8
- package/skills/track-work/scripts/lib/transitions.mjs +79 -4
- package/skills/track-work/scripts/working-record.mjs +34 -12
- package/skills/verify-work/SKILL.md +29 -20
- package/skills/verify-work/references/browser-runtime-evidence.md +1 -5
- package/skills/verify-work/references/integration-evidence.md +2 -0
- package/skills/verify-work/references/performance-evidence.md +3 -1
- package/skills/verify-work/references/test-design.md +3 -1
- package/skills/workflow/SKILL.md +65 -21
- package/skills/workflow/references/domain-skill-composition.md +5 -3
- package/skills/write-docs/SKILL.md +83 -0
- package/skills/write-docs/references/documentation-shapes.md +119 -0
- package/skills/write-docs/scripts/docs-check.mjs +139 -0
- package/skills/write-plan/SKILL.md +40 -40
- package/skills/write-plan/references/plan-shapes.md +1 -1
- package/skills/write-skill/SKILL.md +107 -147
- package/skills/write-skill/references/activation-boundaries.md +2 -0
- package/skills/write-skill/references/agent-first-instructions.md +22 -10
- package/skills/write-skill/references/progressive-disclosure.md +4 -2
- package/skills/write-skill/references/skill-dependency-graphs.md +2 -0
- package/skills/write-skill/scripts/lib/similarity.mjs +56 -0
- package/skills/write-skill/scripts/skill-author.mjs +18 -2
- package/skills/write-spec/SKILL.md +34 -41
- package/skills/write-spec/references/artifact-standards.md +1 -1
- package/skills/write-spec/references/decision-records.md +2 -0
- package/skills/write-spec/references/spec-shapes.md +1 -1
- package/capabilities/context-virtualization/SKILL.md +0 -103
- package/capabilities/conversation-history/SKILL.md +0 -53
- package/hooks/tests/check-host-adapters.test.mjs +0 -82
- package/hooks/tests/check-runtime-context-hook.sh +0 -212
- package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -2181
- package/pi-extension/dist/context-virtualization/commands.js +0 -89
- package/pi-extension/dist/context-virtualization/projector.js +0 -42
- package/pi-extension/dist/context-virtualization/runtime.js +0 -378
- package/pi-extension/dist/context-virtualization/state.js +0 -57
- package/pi-extension/dist/context-virtualization/types.js +0 -10
- package/pi-extension/dist/conversation-history/passages.js +0 -66
- package/pi-extension/dist/conversation-history/ranking.js +0 -105
- package/pi-extension/dist/conversation-history/runtime.js +0 -226
- package/pi-extension/dist/conversation-history/search.js +0 -56
- package/pi-extension/dist/conversation-history/types.js +0 -1
- package/pi-extension/dist/freeflow-context/resolver.js +0 -120
- package/pi-extension/dist/freeflow-context/runtime.js +0 -80
- package/pi-extension/dist/freeflow-context/source-projector.js +0 -95
- package/pi-extension/dist/freeflow-context/tool.js +0 -314
- package/pi-extension/dist/freeflow-context/types.js +0 -12
- package/pi-extension/dist/freeflow-context/visibility.js +0 -28
- package/pi-extension/dist/integrations/mcp-config.js +0 -29
- package/pi-extension/dist/runtime/runtime-context.js +0 -754
- package/pi-extension/dist/runtime/runtime-identity.js +0 -5
- package/pi-extension/dist/session-sources/provenance.js +0 -32
- package/pi-extension/dist/ui/text-component.js +0 -57
- package/pi-extension/src/cognitive-routing-v2/budget.ts +0 -42
- package/pi-extension/src/cognitive-routing-v2/config.ts +0 -173
- package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -375
- package/pi-extension/src/cognitive-routing-v2/render.ts +0 -277
- package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -2241
- package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -180
- package/pi-extension/src/cognitive-routing-v2/state.ts +0 -839
- package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -62
- package/pi-extension/src/cognitive-routing-v2/types.ts +0 -254
- package/pi-extension/src/context-virtualization/commands.ts +0 -111
- package/pi-extension/src/context-virtualization/projector.ts +0 -62
- package/pi-extension/src/context-virtualization/runtime.ts +0 -428
- package/pi-extension/src/context-virtualization/state.ts +0 -79
- package/pi-extension/src/context-virtualization/types.ts +0 -92
- package/pi-extension/src/conversation-history/passages.ts +0 -81
- package/pi-extension/src/conversation-history/ranking.ts +0 -155
- package/pi-extension/src/conversation-history/runtime.ts +0 -250
- package/pi-extension/src/conversation-history/search.ts +0 -79
- package/pi-extension/src/conversation-history/types.ts +0 -31
- package/pi-extension/src/freeflow-context/resolver.ts +0 -139
- package/pi-extension/src/freeflow-context/runtime.ts +0 -100
- package/pi-extension/src/freeflow-context/source-projector.ts +0 -106
- package/pi-extension/src/freeflow-context/tool.ts +0 -366
- package/pi-extension/src/freeflow-context/types.ts +0 -70
- package/pi-extension/src/freeflow-context/visibility.ts +0 -53
- package/pi-extension/src/index.ts +0 -390
- package/pi-extension/src/integrations/mcp-config.ts +0 -32
- package/pi-extension/src/provider-support/astra/adapter.ts +0 -108
- package/pi-extension/src/provider-support/astra/history.ts +0 -145
- package/pi-extension/src/provider-support/astra/index.ts +0 -12
- package/pi-extension/src/provider-support/astra/session-state.ts +0 -113
- package/pi-extension/src/provider-support/index.ts +0 -5
- package/pi-extension/src/runtime/request-history.ts +0 -243
- package/pi-extension/src/runtime/runtime-context.ts +0 -860
- package/pi-extension/src/runtime/runtime-identity.ts +0 -8
- package/pi-extension/src/session-sources/events.ts +0 -230
- package/pi-extension/src/session-sources/provenance.ts +0 -39
- package/pi-extension/src/session-sources/read-only-session.ts +0 -170
- package/pi-extension/src/session-sources/sources.ts +0 -334
- package/pi-extension/src/settings/settings-tui.ts +0 -501
- package/pi-extension/src/settings/settings-ui.ts +0 -1652
- package/pi-extension/src/ui/text-component.ts +0 -66
- package/pi-extension/tests/cache-reuse/history.test.js +0 -117
- package/pi-extension/tests/cache-reuse/native.test.js +0 -91
- package/pi-extension/tests/cache-reuse/settings.test.js +0 -211
- package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -577
- package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
- package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +0 -557
- package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -474
- package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
- package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -300
- package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
- package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -1034
- package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -244
- package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -423
- package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
- package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -586
- package/pi-extension/tests/context-virtualization/extension.test.js +0 -775
- package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
- package/pi-extension/tests/context-virtualization/runtime.test.js +0 -230
- package/pi-extension/tests/conversation-history/runtime.test.js +0 -98
- package/pi-extension/tests/conversation-history/search.test.js +0 -97
- package/pi-extension/tests/fixtures/pi-host.js +0 -4
- package/pi-extension/tests/fixtures/routing-native.js +0 -191
- package/pi-extension/tests/integration/mode-free-core.test.js +0 -220
- package/pi-extension/tests/integration/pi-extension.test.js +0 -1447
- package/pi-extension/tests/integration/prompt-architecture.test.js +0 -447
- package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
- package/pi-extension/tests/provider-support/astra-boundaries.test.js +0 -75
- package/pi-extension/tests/provider-support/astra.test.js +0 -306
- package/pi-extension/tests/provider-support/cli.test.js +0 -92
- package/pi-extension/tests/provider-support/native.test.js +0 -183
- package/pi-extension/tests/settings/settings-tui.test.js +0 -243
- package/pi-extension/tsconfig.json +0 -16
- package/runtime/prompts/context-virtualization.md +0 -3
- package/runtime/prompts/conversation-history.md +0 -3
- package/skills/design-for-depth/references/software-design-philosophy.md +0 -202
- /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/budget.js +0 -0
- /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +0 -0
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { ContextAssembler } from "./assembler.js";
|
|
3
|
+
import { EventStore } from "./event-store.js";
|
|
4
|
+
import { ToolGate } from "./gate.js";
|
|
5
|
+
import { Handoffs } from "./handoffs.js";
|
|
6
|
+
import { ToolHandlers } from "./handlers.js";
|
|
7
|
+
import { ModelControl } from "./model-control.js";
|
|
8
|
+
import { RoutingSession } from "./session.js";
|
|
9
|
+
import { RoutingStatus } from "./status.js";
|
|
10
|
+
import { isTaskEvidence } from "./sources.js";
|
|
11
|
+
import { PROFILES, canonical, isWorkerProfile, requireCondition as check, samePair } from "./types.js";
|
|
12
|
+
/**
|
|
13
|
+
* Cognitive Routing as the Pi extension sees it. Binds routing to the current session, follows ancestry and
|
|
14
|
+
* configuration changes, handles /freeflow profile and resume commands, and forwards each host hook to the part that
|
|
15
|
+
* owns it: model control, status, the tool gate, request assembly, handoffs, and the routing tools.
|
|
16
|
+
*/
|
|
17
|
+
export class RoutingRuntime {
|
|
18
|
+
pi;
|
|
19
|
+
packageRoots;
|
|
20
|
+
/** State shared with every part of routing for the bound session. */
|
|
21
|
+
session = new RoutingSession();
|
|
22
|
+
models;
|
|
23
|
+
status;
|
|
24
|
+
gate;
|
|
25
|
+
assembler;
|
|
26
|
+
handoffs;
|
|
27
|
+
tools;
|
|
28
|
+
targetSignature;
|
|
29
|
+
constructor(pi, packageRoots = []) {
|
|
30
|
+
this.pi = pi;
|
|
31
|
+
this.packageRoots = packageRoots;
|
|
32
|
+
this.models = new ModelControl(this.session, this.pi);
|
|
33
|
+
this.status = new RoutingStatus(this.session, this.models);
|
|
34
|
+
this.gate = new ToolGate(this.session, this.packageRoots);
|
|
35
|
+
this.assembler = new ContextAssembler(this.session, this.pi, this.models);
|
|
36
|
+
this.handoffs = new Handoffs(this.session, this.pi, this.models, this.assembler);
|
|
37
|
+
this.tools = new ToolHandlers(this.session, this.models, this.gate, this.assembler, this.status);
|
|
38
|
+
}
|
|
39
|
+
get projectionEnabled() {
|
|
40
|
+
return this.session.projectionEnabled;
|
|
41
|
+
}
|
|
42
|
+
async settled(ctx) {
|
|
43
|
+
if (!this.session.store || !this.session.supported() || this.session.store.blocked || !ctx.isIdle?.()) return;
|
|
44
|
+
this.session.ctx = ctx;
|
|
45
|
+
this.session.retireUnbound(
|
|
46
|
+
"Native run settled without a complete source binding; prior effects remain unresolved.",
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
/** The Coordinator's model while a delegated worker holds the assignment; the Coordinator resumes on return. */
|
|
50
|
+
suspendedCoordinator() {
|
|
51
|
+
try {
|
|
52
|
+
const state = this.session.stateData();
|
|
53
|
+
if (
|
|
54
|
+
!this.session.supported() ||
|
|
55
|
+
state.control !== "automatic" ||
|
|
56
|
+
!isWorkerProfile(state.profile) ||
|
|
57
|
+
!state.assignmentId
|
|
58
|
+
)
|
|
59
|
+
return;
|
|
60
|
+
const pair = this.session.profilePair("coordinator");
|
|
61
|
+
return { provider: pair.provider, modelId: pair.modelId, requester: "coordinator" };
|
|
62
|
+
} catch {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async bind(ctx, capability, startup = false) {
|
|
67
|
+
this.session.token = randomUUID();
|
|
68
|
+
this.session.ctx = ctx;
|
|
69
|
+
this.session.capability = capability;
|
|
70
|
+
this.session.resetTurn();
|
|
71
|
+
this.session.manualHold = undefined;
|
|
72
|
+
this.session.automaticControl = false;
|
|
73
|
+
this.models.applying = undefined;
|
|
74
|
+
this.models.externalChange = false;
|
|
75
|
+
this.session.error = undefined;
|
|
76
|
+
this.session.projectionError = undefined;
|
|
77
|
+
this.session.operations = Promise.resolve();
|
|
78
|
+
this.targetSignature = canonical({ delegation: capability.delegation, profiles: capability.profiles });
|
|
79
|
+
this.session.suppressed = startup && process.argv.some((a) => /^(--model|--thinking)(=|$)/.test(a));
|
|
80
|
+
this.session.store = new EventStore(this.pi, ctx.sessionManager);
|
|
81
|
+
const subject = this.session.subject();
|
|
82
|
+
if (!capability.effective || this.session.suppressed) return;
|
|
83
|
+
try {
|
|
84
|
+
await this.session.store.reconcile();
|
|
85
|
+
this.session.guard(subject);
|
|
86
|
+
const state = this.session.stateData();
|
|
87
|
+
this.session.manualHold = state.control === "manual" ? state.profile : undefined;
|
|
88
|
+
this.session.automaticControl = !state.events.size || state.control === "automatic";
|
|
89
|
+
await this.models.validateProfilePairs(this.session.profilePairs(this.session.requiredProfiles(state)));
|
|
90
|
+
this.models.announcePresets(ctx);
|
|
91
|
+
const interrupted = this.handoffs.interruptedRun(state);
|
|
92
|
+
const resumable = this.handoffs.resumableAssignment(state);
|
|
93
|
+
this.session.retireUnbound("Session rebind found an unfinished execution; no task effects replayed.");
|
|
94
|
+
if (!state.events.size) {
|
|
95
|
+
await this.models.transition(
|
|
96
|
+
this.session.profilePair("coordinator"),
|
|
97
|
+
() =>
|
|
98
|
+
this.session.append({
|
|
99
|
+
type: "control",
|
|
100
|
+
control: "automatic",
|
|
101
|
+
profile: "coordinator",
|
|
102
|
+
reason: "Initial routing activation",
|
|
103
|
+
}),
|
|
104
|
+
subject,
|
|
105
|
+
);
|
|
106
|
+
} else if (
|
|
107
|
+
state.control === "automatic" &&
|
|
108
|
+
state.profile &&
|
|
109
|
+
!samePair(this.models.intended(), this.session.profilePair(state.profile))
|
|
110
|
+
) {
|
|
111
|
+
// Reload reconstructs responsibility; it does not silently reapply the last setter.
|
|
112
|
+
await this.models.transition(
|
|
113
|
+
this.session.profilePair("coordinator"),
|
|
114
|
+
() =>
|
|
115
|
+
this.session.append({
|
|
116
|
+
type: "control",
|
|
117
|
+
control: "automatic",
|
|
118
|
+
profile: "coordinator",
|
|
119
|
+
reason: "Rebind reconciles historical responsibility with current host control",
|
|
120
|
+
}),
|
|
121
|
+
subject,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
// Only a run cut off mid-flight resumes on its own; reopening an idle session never starts work.
|
|
125
|
+
if (interrupted && ctx.hasUI) {
|
|
126
|
+
const token = this.session.token;
|
|
127
|
+
setTimeout(() => void this.handoffs.resumeAfterCrash(ctx, token), 0);
|
|
128
|
+
} else if (resumable)
|
|
129
|
+
ctx.ui?.notify?.(
|
|
130
|
+
`The ${resumable.worker} assignment is unchanged. Run /freeflow resume to continue it; a new message goes to Coordinator.`,
|
|
131
|
+
"info",
|
|
132
|
+
);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (this.session.current(subject)) this.session.mark(error);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Write routing events staged before the session's first prompt; nothing to write once routing is unbound. */
|
|
138
|
+
writeStaged(events) {
|
|
139
|
+
if (!this.session.store || !events.length) return;
|
|
140
|
+
try {
|
|
141
|
+
this.session.store.writeStaged(events);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
this.session.mark(error);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
unbind() {
|
|
147
|
+
this.session.token = randomUUID();
|
|
148
|
+
this.session.store = undefined;
|
|
149
|
+
this.session.ctx = undefined;
|
|
150
|
+
this.session.resetTurn();
|
|
151
|
+
}
|
|
152
|
+
async refresh(ctx, capability) {
|
|
153
|
+
this.session.ctx = ctx;
|
|
154
|
+
const was = this.session.capability?.effective === true;
|
|
155
|
+
const signature = canonical({ delegation: capability.delegation, profiles: capability.profiles });
|
|
156
|
+
if (this.session.capability && (was !== capability.effective || signature !== this.targetSignature))
|
|
157
|
+
this.session.revision++;
|
|
158
|
+
this.session.capability = capability;
|
|
159
|
+
if (!capability.effective) {
|
|
160
|
+
this.session.turn = undefined;
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (!this.session.store) {
|
|
164
|
+
await this.bind(ctx, capability);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (!was) {
|
|
168
|
+
const subject = this.session.subject();
|
|
169
|
+
this.session.suppressed = false;
|
|
170
|
+
try {
|
|
171
|
+
await this.session.store.reconcile();
|
|
172
|
+
this.session.guard(subject);
|
|
173
|
+
this.session.error = undefined;
|
|
174
|
+
await this.models.transition(
|
|
175
|
+
this.session.profilePair("coordinator"),
|
|
176
|
+
() =>
|
|
177
|
+
this.session.append({
|
|
178
|
+
type: "control",
|
|
179
|
+
control: "automatic",
|
|
180
|
+
profile: "coordinator",
|
|
181
|
+
reason: "Capability re-enabled; Coordinator reconciliation",
|
|
182
|
+
}),
|
|
183
|
+
subject,
|
|
184
|
+
);
|
|
185
|
+
this.session.automaticControl = true;
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (this.session.current(subject)) this.session.mark(error);
|
|
188
|
+
}
|
|
189
|
+
} else if (this.targetSignature && signature !== this.targetSignature) {
|
|
190
|
+
this.session.error = "configuration_changed: reconcile profile configuration before automatic execution";
|
|
191
|
+
this.session.announceBlock(ctx);
|
|
192
|
+
}
|
|
193
|
+
if (
|
|
194
|
+
canonical({ delegation: this.session.capability?.delegation, profiles: this.session.capability?.profiles }) ===
|
|
195
|
+
signature
|
|
196
|
+
)
|
|
197
|
+
this.targetSignature = signature;
|
|
198
|
+
this.models.announcePresets(ctx);
|
|
199
|
+
}
|
|
200
|
+
async ancestryChanged(ctx, navigation = true) {
|
|
201
|
+
this.session.revision++;
|
|
202
|
+
this.session.ctx = ctx;
|
|
203
|
+
this.session.resetTurn();
|
|
204
|
+
if (!this.session.store || !this.session.supported()) return;
|
|
205
|
+
const subject = this.session.subject();
|
|
206
|
+
try {
|
|
207
|
+
await this.session.store.reconcile();
|
|
208
|
+
this.session.guard(subject);
|
|
209
|
+
this.session.error = undefined;
|
|
210
|
+
const state = this.session.stateData();
|
|
211
|
+
await this.models.validateProfilePairs(this.session.profilePairs(this.session.requiredProfiles(state)));
|
|
212
|
+
this.session.retireUnbound(
|
|
213
|
+
"Selected historical ancestry ends before execution binding; effects are not replayed.",
|
|
214
|
+
);
|
|
215
|
+
if (this.session.manualHold) {
|
|
216
|
+
const held = this.session.manualHold;
|
|
217
|
+
await this.models.transition(
|
|
218
|
+
this.session.profilePair(held),
|
|
219
|
+
() =>
|
|
220
|
+
this.session.append({
|
|
221
|
+
type: "control",
|
|
222
|
+
control: "manual",
|
|
223
|
+
profile: held,
|
|
224
|
+
reason: "Current explicit manual hold survives navigation",
|
|
225
|
+
}),
|
|
226
|
+
subject,
|
|
227
|
+
);
|
|
228
|
+
} else if (
|
|
229
|
+
(this.session.automaticControl || !state.events.size) &&
|
|
230
|
+
(navigation || !samePair(this.models.intended(), this.session.profilePair(state.profile ?? "coordinator")))
|
|
231
|
+
) {
|
|
232
|
+
await this.models.transition(
|
|
233
|
+
this.session.profilePair("coordinator"),
|
|
234
|
+
() =>
|
|
235
|
+
this.session.append({
|
|
236
|
+
type: "control",
|
|
237
|
+
control: "automatic",
|
|
238
|
+
profile: "coordinator",
|
|
239
|
+
reason: "Coordinator reconciles selected native ancestry",
|
|
240
|
+
}),
|
|
241
|
+
subject,
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (this.session.current(subject)) this.session.mark(error);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async command(args, ctx) {
|
|
249
|
+
const words = args.trim().split(/\s+/);
|
|
250
|
+
if (!["profile", "resume"].includes(words[0])) return false;
|
|
251
|
+
try {
|
|
252
|
+
if (words[0] === "profile" && words[1] === "history") {
|
|
253
|
+
check(words.length === 2 || (words.length === 3 && words[2] === "diagnostics"), "invalid_history_command");
|
|
254
|
+
ctx.ui.notify(
|
|
255
|
+
JSON.stringify(
|
|
256
|
+
words[2] === "diagnostics"
|
|
257
|
+
? this.status.detail(30)
|
|
258
|
+
: this.tools.inspectUnit({ view: "history", limit: 30 }),
|
|
259
|
+
),
|
|
260
|
+
"info",
|
|
261
|
+
);
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
check(ctx.isIdle?.(), "not_idle");
|
|
265
|
+
this.session.ctx = ctx;
|
|
266
|
+
if (words[0] === "resume" && words.length === 1) {
|
|
267
|
+
await this.handoffs.resume(ctx);
|
|
268
|
+
return true;
|
|
269
|
+
}
|
|
270
|
+
check(
|
|
271
|
+
words.length === 2 && [...PROFILES, "auto"].includes(words[1]),
|
|
272
|
+
"invalid_profile_command",
|
|
273
|
+
"Use /freeflow profile coordinator|helper|executor|auto|history, or /freeflow resume.",
|
|
274
|
+
);
|
|
275
|
+
const result =
|
|
276
|
+
words[1] === "auto" ? await this.models.setAutomaticControl() : await this.models.setManualProfile(words[1]);
|
|
277
|
+
ctx.ui.notify(JSON.stringify(result), result.status === "blocked" ? "warning" : "info");
|
|
278
|
+
} catch (error) {
|
|
279
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "warning");
|
|
280
|
+
}
|
|
281
|
+
return true;
|
|
282
|
+
}
|
|
283
|
+
beforeRun(ctx, fromPrompt = true) {
|
|
284
|
+
return this.models.beforeRun(ctx, fromPrompt);
|
|
285
|
+
}
|
|
286
|
+
runStarted() {
|
|
287
|
+
this.models.runStarted();
|
|
288
|
+
}
|
|
289
|
+
startedByMessage(message) {
|
|
290
|
+
return this.models.startedByMessage(message);
|
|
291
|
+
}
|
|
292
|
+
nativeChange(ctx) {
|
|
293
|
+
return this.models.nativeChange(ctx);
|
|
294
|
+
}
|
|
295
|
+
cycleManualProfile() {
|
|
296
|
+
return this.models.cycleManualProfile();
|
|
297
|
+
}
|
|
298
|
+
setManualProfile(profile, _mechanism) {
|
|
299
|
+
return this.models.setManualProfile(profile, _mechanism);
|
|
300
|
+
}
|
|
301
|
+
setAutomaticControl(_mechanism) {
|
|
302
|
+
return this.models.setAutomaticControl(_mechanism);
|
|
303
|
+
}
|
|
304
|
+
sessionProfileOverrides() {
|
|
305
|
+
return this.models.sessionProfileOverrides();
|
|
306
|
+
}
|
|
307
|
+
sessionDelegationOverride() {
|
|
308
|
+
return this.models.sessionDelegationOverride();
|
|
309
|
+
}
|
|
310
|
+
setSessionDelegationOverride(override, mechanism = "Session delegation override") {
|
|
311
|
+
return this.models.setSessionDelegationOverride(override, mechanism);
|
|
312
|
+
}
|
|
313
|
+
setSessionProfileOverride(profile, override, mechanism = "Session profile override") {
|
|
314
|
+
return this.models.setSessionProfileOverride(profile, override, mechanism);
|
|
315
|
+
}
|
|
316
|
+
resetSessionProfileOverrides(mechanism = "Reset session profile overrides") {
|
|
317
|
+
return this.models.resetSessionProfileOverrides(mechanism);
|
|
318
|
+
}
|
|
319
|
+
preflight(event, ctx) {
|
|
320
|
+
return this.gate.preflight(event, ctx);
|
|
321
|
+
}
|
|
322
|
+
operationScope(ctx = this.session.ctx) {
|
|
323
|
+
return this.gate.operationScope(ctx);
|
|
324
|
+
}
|
|
325
|
+
observationScope() {
|
|
326
|
+
return this.gate.observationScope();
|
|
327
|
+
}
|
|
328
|
+
admitOperation(scope, effect, _operation, ctx = this.session.ctx) {
|
|
329
|
+
return this.gate.admitOperation(scope, effect, _operation, ctx);
|
|
330
|
+
}
|
|
331
|
+
admitProgram(scope, ctx = this.session.ctx) {
|
|
332
|
+
return this.gate.admitProgram(scope, ctx);
|
|
333
|
+
}
|
|
334
|
+
resultReadAccess(id) {
|
|
335
|
+
return this.gate.resultReadAccess(id);
|
|
336
|
+
}
|
|
337
|
+
budgetNotice(messages, ctx) {
|
|
338
|
+
return this.assembler.budgetNotice(messages, ctx);
|
|
339
|
+
}
|
|
340
|
+
context(ctx, incoming) {
|
|
341
|
+
return this.assembler.context(ctx, incoming);
|
|
342
|
+
}
|
|
343
|
+
messageEnd(message) {
|
|
344
|
+
return this.handoffs.messageEnd(message);
|
|
345
|
+
}
|
|
346
|
+
turnEnd(event, ctx) {
|
|
347
|
+
return this.handoffs.turnEnd(event, ctx);
|
|
348
|
+
}
|
|
349
|
+
state() {
|
|
350
|
+
return this.status.state();
|
|
351
|
+
}
|
|
352
|
+
/** The assignment in progress, if any; Freeflow compaction records it so routing can tell the worker it compacted. */
|
|
353
|
+
currentAssignment() {
|
|
354
|
+
if (!this.state().effective) return undefined;
|
|
355
|
+
return this.session.stateData().assignmentId ?? undefined;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* The assignment in progress, for compaction: the entries of the tool results it produced (task evidence only) and
|
|
359
|
+
* the refs already selected as its evidence. Undefined when no worker holds an assignment.
|
|
360
|
+
*/
|
|
361
|
+
assignmentResults() {
|
|
362
|
+
try {
|
|
363
|
+
const state = this.session.stateData();
|
|
364
|
+
const assignmentId = state.assignmentId;
|
|
365
|
+
if (!this.state().effective || !assignmentId) return undefined;
|
|
366
|
+
const entryIds = new Set();
|
|
367
|
+
for (const source of this.session.sources().byRef.values())
|
|
368
|
+
if (source.assignmentId === assignmentId && isTaskEvidence(source)) entryIds.add(source.entry.id);
|
|
369
|
+
return { entryIds, selected: new Set(state.selections.get(assignmentId)?.selected ?? []) };
|
|
370
|
+
} catch {
|
|
371
|
+
return undefined;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/** A source ref's tool result, for compaction to carry; only task evidence, the results routing lets be selected. */
|
|
375
|
+
evidenceSource(ref) {
|
|
376
|
+
try {
|
|
377
|
+
const source = this.session.sources().byRef.get(ref);
|
|
378
|
+
if (!source || !isTaskEvidence(source)) return undefined;
|
|
379
|
+
const text = (source.message.content ?? [])
|
|
380
|
+
.map((part) => (part?.type === "text" ? part.text : part?.type === "image" ? "[image]" : ""))
|
|
381
|
+
.join("");
|
|
382
|
+
return { tool: source.message.toolName ?? "tool", text };
|
|
383
|
+
} catch {
|
|
384
|
+
return undefined;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
setResultGrantPort(port) {
|
|
388
|
+
return this.tools.setResultGrantPort(port);
|
|
389
|
+
}
|
|
390
|
+
setEffectFencePort(port) {
|
|
391
|
+
return this.tools.setEffectFencePort(port);
|
|
392
|
+
}
|
|
393
|
+
invoke(name, callId, input, signal, ctx) {
|
|
394
|
+
return this.tools.invoke(name, callId, input, signal, ctx);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
@@ -69,6 +69,7 @@ export const ROUTING_SCHEMAS = {
|
|
|
69
69
|
operation: operation("recover"),
|
|
70
70
|
request: string(),
|
|
71
71
|
paths: { type: "array", maxItems: 32, items: string(4096) },
|
|
72
|
+
results: { type: "array", maxItems: 32, uniqueItems: true, items: string(256) },
|
|
72
73
|
},
|
|
73
74
|
["operation", "request"],
|
|
74
75
|
),
|
|
@@ -140,6 +141,48 @@ for (const schema of Object.values(ROUTING_SCHEMAS)) {
|
|
|
140
141
|
description:
|
|
141
142
|
"For add, use exact eligible visible refs directly when their identity and eligibility are clear; inspect when identity, eligibility, representation, or selection state is unclear. Never add refs marked not offered for new evidence selection. For remove, use currently selected or unresolved refs; a non-selectable ref may be named to clear its unresolved request and requires reason.",
|
|
142
143
|
};
|
|
144
|
+
// The provider sees one flattened root, so each field names the operations whose strict shape accepts it.
|
|
145
|
+
const operations = schema.oneOf.map((branch) => branch.properties.operation.enum[0]);
|
|
146
|
+
for (const [field, property] of Object.entries(schema.properties)) {
|
|
147
|
+
if (field === "operation") continue;
|
|
148
|
+
const accepting = operations.filter((_op, i) => Object.hasOwn(schema.oneOf[i].properties, field));
|
|
149
|
+
if (accepting.length === operations.length) continue;
|
|
150
|
+
const scope = `Only for operation: ${accepting.join(", ")}.`;
|
|
151
|
+
schema.properties[field] = {
|
|
152
|
+
...property,
|
|
153
|
+
description: property.description ? `${property.description} ${scope}` : scope,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const expected = (schema) =>
|
|
158
|
+
schema.enum
|
|
159
|
+
? `one of ${schema.enum.join(", ")}`
|
|
160
|
+
: schema.type === "string"
|
|
161
|
+
? `a non-empty string of at most ${schema.maxLength} characters`
|
|
162
|
+
: schema.type === "array"
|
|
163
|
+
? `an array of at most ${schema.maxItems} items`
|
|
164
|
+
: schema.type === "integer"
|
|
165
|
+
? `an integer from ${schema.minimum} to ${schema.maximum}`
|
|
166
|
+
: `type ${schema.type}`;
|
|
167
|
+
/** Explain why routing arguments match no strict operation shape, naming what to change. */
|
|
168
|
+
export function explainRoutingArguments(name, input) {
|
|
169
|
+
const schema = ROUTING_SCHEMAS[name];
|
|
170
|
+
const operations = schema.oneOf.map((branch) => branch.properties.operation.enum[0]);
|
|
171
|
+
const operation = isObject(input) ? input.operation : undefined;
|
|
172
|
+
const branch = schema.oneOf.find((b) => b.properties.operation.enum[0] === operation);
|
|
173
|
+
if (!isObject(input) || !branch)
|
|
174
|
+
return `Invalid ${name} arguments: operation must be one of ${operations.join(", ")}. No operation was accepted.`;
|
|
175
|
+
const allowed = Object.keys(branch.properties);
|
|
176
|
+
const problems = [];
|
|
177
|
+
const unknown = Object.keys(input).filter((field) => !allowed.includes(field));
|
|
178
|
+
if (unknown.length) problems.push(`remove field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")}`);
|
|
179
|
+
const missing = branch.required.filter((field) => !Object.hasOwn(input, field));
|
|
180
|
+
if (missing.length) problems.push(`missing required field${missing.length > 1 ? "s" : ""} ${missing.join(", ")}`);
|
|
181
|
+
for (const field of allowed)
|
|
182
|
+
if (Object.hasOwn(input, field) && !matches(input[field], branch.properties[field]))
|
|
183
|
+
problems.push(`${field} must be ${expected(branch.properties[field])}`);
|
|
184
|
+
if (!problems.length) problems.push("arguments do not match this operation's shape");
|
|
185
|
+
return `Invalid ${name} arguments for operation ${operation}: ${problems.join("; ")}. Allowed fields: ${allowed.join(", ")}. No operation was accepted.`;
|
|
143
186
|
}
|
|
144
187
|
export function matches(value, schema) {
|
|
145
188
|
if (schema.oneOf) return schema.oneOf.filter((branch) => matches(value, branch)).length === 1;
|
|
@@ -164,10 +207,3 @@ export function matches(value, schema) {
|
|
|
164
207
|
return Number.isSafeInteger(value) && value >= schema.minimum && value <= schema.maximum;
|
|
165
208
|
return false;
|
|
166
209
|
}
|
|
167
|
-
export function schemaForProfile(name, coordinator) {
|
|
168
|
-
const schema = ROUTING_SCHEMAS[name];
|
|
169
|
-
if (name !== "freeflow_unit" || coordinator) return schema;
|
|
170
|
-
const branches = schema.oneOf.filter((b) => b.properties.operation.enum[0] === "inspect");
|
|
171
|
-
const properties = Object.assign({}, ...branches.map((b) => b.properties));
|
|
172
|
-
return { ...schema, properties, oneOf: branches };
|
|
173
|
-
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Sources } from "./sources.js";
|
|
3
|
+
import { ViewCache } from "./projection.js";
|
|
4
|
+
import { pairFromProfile } from "./config.js";
|
|
5
|
+
import { initialState } from "./state.js";
|
|
6
|
+
import { RoutingError, isWorkerProfile, requireCondition as check, samePair, workersForDelegation } from "./types.js";
|
|
7
|
+
import { cachedBranch } from "../host/branch.js";
|
|
8
|
+
const STAGED_CONTROL = new Set(["control", "profile-overrides", "delegation-override"]);
|
|
9
|
+
export const ROUTING_RECOVERY_HINT =
|
|
10
|
+
"Run /freeflow profile auto to reconcile routing, or /freeflow resume to continue saved work.";
|
|
11
|
+
/**
|
|
12
|
+
* State and identity shared by every part of routing for one bound session: the event journal, the host
|
|
13
|
+
* context, the current turn, blocking errors, control mode, and the queue that orders control changes.
|
|
14
|
+
*/
|
|
15
|
+
export class RoutingSession {
|
|
16
|
+
store;
|
|
17
|
+
ctx;
|
|
18
|
+
capability;
|
|
19
|
+
token = randomUUID();
|
|
20
|
+
turn;
|
|
21
|
+
messages = [];
|
|
22
|
+
error;
|
|
23
|
+
projectionError;
|
|
24
|
+
suppressed = false;
|
|
25
|
+
operations = Promise.resolve();
|
|
26
|
+
revision = 0;
|
|
27
|
+
manualHold;
|
|
28
|
+
automaticControl = false;
|
|
29
|
+
sourceCache;
|
|
30
|
+
/** Rendered view messages reused across requests (see ViewCache); rebuilt after a rebind or ancestry change. */
|
|
31
|
+
viewCache = new ViewCache();
|
|
32
|
+
/** Replayed tool results for the current turn, keyed by operation id. */
|
|
33
|
+
receipts = new Map();
|
|
34
|
+
/** Recently served inspection pages, keyed by request; at most eight are kept. */
|
|
35
|
+
pages = new Map();
|
|
36
|
+
get projectionEnabled() {
|
|
37
|
+
return this.supported() && this.capability?.projection === true && this.stateData().control === "automatic";
|
|
38
|
+
}
|
|
39
|
+
/** Forgets everything derived for the current turn: its context view, sources, replay receipts, and pages. */
|
|
40
|
+
resetTurn() {
|
|
41
|
+
this.turn = undefined;
|
|
42
|
+
this.messages = [];
|
|
43
|
+
this.sourceCache = undefined;
|
|
44
|
+
this.viewCache = new ViewCache();
|
|
45
|
+
this.receipts.clear();
|
|
46
|
+
this.pages.clear();
|
|
47
|
+
}
|
|
48
|
+
subject() {
|
|
49
|
+
const branch = cachedBranch(this.store?.reader) ?? [];
|
|
50
|
+
return {
|
|
51
|
+
token: this.token,
|
|
52
|
+
revision: this.revision,
|
|
53
|
+
store: this.store,
|
|
54
|
+
leafId: branch.at(-1)?.id ?? null,
|
|
55
|
+
userId: branch.filter((e) => e.message?.role === "user").at(-1)?.id ?? null,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
current(s) {
|
|
59
|
+
if (s.token !== this.token || s.revision !== this.revision || s.store !== this.store) return false;
|
|
60
|
+
const branch = cachedBranch(this.store?.reader) ?? [];
|
|
61
|
+
return (
|
|
62
|
+
(!s.leafId || branch.some((e) => e.id === s.leafId)) &&
|
|
63
|
+
(branch.filter((e) => e.message?.role === "user").at(-1)?.id ?? null) === s.userId
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
guard(s) {
|
|
67
|
+
check(
|
|
68
|
+
this.current(s),
|
|
69
|
+
"stale_operation",
|
|
70
|
+
"Routing state changed while the operation was waiting; no further effects applied.",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
taskBasis(state, assignmentId) {
|
|
74
|
+
return state.resumeBasis.has(assignmentId)
|
|
75
|
+
? state.resumeBasis.get(assignmentId)
|
|
76
|
+
: state.assignments.get(assignmentId)?.basisUserEntryId;
|
|
77
|
+
}
|
|
78
|
+
delegation(state = this.stateData()) {
|
|
79
|
+
return state.delegationOverride ?? this.capability?.delegation ?? "executor";
|
|
80
|
+
}
|
|
81
|
+
enabledWorkers(state = this.stateData()) {
|
|
82
|
+
return workersForDelegation(this.delegation(state));
|
|
83
|
+
}
|
|
84
|
+
assignedWorker(state, assignmentId = state.assignmentId) {
|
|
85
|
+
const assignment = assignmentId ? state.assignments.get(assignmentId) : undefined;
|
|
86
|
+
const handoff = assignment ? state.handoffs.get(assignment.delegateHandoffId) : undefined;
|
|
87
|
+
check(
|
|
88
|
+
handoff?.kind === "delegate" && handoff.assignmentId === assignment?.id && isWorkerProfile(handoff.to),
|
|
89
|
+
"assignment_worker_missing",
|
|
90
|
+
"The current assignment has no valid recorded worker.",
|
|
91
|
+
);
|
|
92
|
+
return handoff.to;
|
|
93
|
+
}
|
|
94
|
+
requiredProfiles(state = this.stateData(), delegation = this.delegation(state)) {
|
|
95
|
+
const profiles = new Set(["coordinator", ...workersForDelegation(delegation)]);
|
|
96
|
+
if (state.profile) profiles.add(state.profile);
|
|
97
|
+
if (this.manualHold) profiles.add(this.manualHold);
|
|
98
|
+
const assignment = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
99
|
+
if (assignment?.state === "outstanding" || state.recoveryId) profiles.add(this.assignedWorker(state));
|
|
100
|
+
const pending = state.pendingId ? state.handoffs.get(state.pendingId) : undefined;
|
|
101
|
+
if (pending && isWorkerProfile(pending.to)) profiles.add(pending.to);
|
|
102
|
+
return [...profiles];
|
|
103
|
+
}
|
|
104
|
+
retireUnbound(reason) {
|
|
105
|
+
for (const execution of this.stateData().executions.values()) {
|
|
106
|
+
if (!execution.assistantEntryId && !execution.interrupted)
|
|
107
|
+
this.append({ type: "execution-interrupted", executionId: execution.id, reason });
|
|
108
|
+
}
|
|
109
|
+
this.turn = undefined;
|
|
110
|
+
}
|
|
111
|
+
openTurn() {
|
|
112
|
+
if (!this.turn || this.turn.opened) return;
|
|
113
|
+
const t = this.turn;
|
|
114
|
+
this.append({
|
|
115
|
+
type: "execution-opened",
|
|
116
|
+
execution: {
|
|
117
|
+
id: t.id,
|
|
118
|
+
profile: t.profile,
|
|
119
|
+
assignmentId: t.assignmentId,
|
|
120
|
+
recoveryId: t.recoveryId,
|
|
121
|
+
basisUserEntryId: t.basisUserEntryId,
|
|
122
|
+
pair: t.pair,
|
|
123
|
+
resultEntryIds: [],
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
t.opened = true;
|
|
127
|
+
}
|
|
128
|
+
stateData() {
|
|
129
|
+
return this.store?.state() ?? initialState();
|
|
130
|
+
}
|
|
131
|
+
sources(state = this.stateData()) {
|
|
132
|
+
const branch = cachedBranch(this.ctx.sessionManager);
|
|
133
|
+
const cache = this.sourceCache;
|
|
134
|
+
// The cached branch is the same array until the leaf moves, so an unchanged branch needs no filtering.
|
|
135
|
+
if (cache && cache.branch === branch && cache.authors === state.authors.size) return cache.source;
|
|
136
|
+
const entries = branch.filter((e) =>
|
|
137
|
+
["message", "custom_message", "compaction", "branch_summary"].includes(e.type),
|
|
138
|
+
);
|
|
139
|
+
if (
|
|
140
|
+
cache &&
|
|
141
|
+
cache.authors === state.authors.size &&
|
|
142
|
+
entries.length === cache.entries.length &&
|
|
143
|
+
entries.every((e, i) => e === cache.entries[i])
|
|
144
|
+
) {
|
|
145
|
+
cache.branch = branch;
|
|
146
|
+
return cache.source;
|
|
147
|
+
}
|
|
148
|
+
const active = this.ctx.sessionManager.buildContextEntries?.();
|
|
149
|
+
const activeIds = active ? new Set(active.map((e) => e.id)) : undefined;
|
|
150
|
+
const source = cache?.source ?? new Sources([], state);
|
|
151
|
+
source.refresh(entries, state, activeIds);
|
|
152
|
+
this.sourceCache = { branch, entries, authors: state.authors.size, source };
|
|
153
|
+
return source;
|
|
154
|
+
}
|
|
155
|
+
observed(ctx = this.ctx) {
|
|
156
|
+
return ctx?.model?.provider && ctx?.model?.id && ctx?.thinkingLevel
|
|
157
|
+
? { provider: ctx.model.provider, modelId: ctx.model.id, thinking: ctx.thinkingLevel }
|
|
158
|
+
: undefined;
|
|
159
|
+
}
|
|
160
|
+
supported() {
|
|
161
|
+
return !!this.capability?.effective && !this.suppressed;
|
|
162
|
+
}
|
|
163
|
+
append(data, op, step) {
|
|
164
|
+
check(this.store, "routing_unavailable");
|
|
165
|
+
// Control changes made while no run is active affect no request until the next prompt; stage them there.
|
|
166
|
+
const stage = STAGED_CONTROL.has(data.type) && this.ctx?.isIdle?.() !== false;
|
|
167
|
+
return this.store.append(this.store.make(data, op, step), stage);
|
|
168
|
+
}
|
|
169
|
+
enqueue(action) {
|
|
170
|
+
const token = this.token;
|
|
171
|
+
const result = this.operations.then(() => {
|
|
172
|
+
check(token === this.token, "stale_instance");
|
|
173
|
+
return action();
|
|
174
|
+
});
|
|
175
|
+
this.operations = result.catch(() => {});
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
mark(error) {
|
|
179
|
+
if (this.error && error instanceof RoutingError && error.code === "routing_blocked") return;
|
|
180
|
+
this.error =
|
|
181
|
+
error instanceof RoutingError
|
|
182
|
+
? `${error.code}: ${error.message}`
|
|
183
|
+
: error instanceof Error
|
|
184
|
+
? error.message
|
|
185
|
+
: String(error);
|
|
186
|
+
}
|
|
187
|
+
announced;
|
|
188
|
+
// Tell the user once per distinct block; routing stays blocked until an explicit control clears it.
|
|
189
|
+
announceBlock(ctx) {
|
|
190
|
+
if (!this.error || this.announced === this.error) return;
|
|
191
|
+
this.announced = this.error;
|
|
192
|
+
ctx?.ui?.notify?.(`Cognitive Routing blocked: ${this.error}. ${ROUTING_RECOVERY_HINT}`, "warning");
|
|
193
|
+
}
|
|
194
|
+
assertAvailable(profile) {
|
|
195
|
+
check(
|
|
196
|
+
this.supported() && this.store && !this.error && !this.store.blocked,
|
|
197
|
+
"routing_unavailable",
|
|
198
|
+
this.error ?? this.store?.blocked ?? "Routing is inactive.",
|
|
199
|
+
);
|
|
200
|
+
const state = this.stateData();
|
|
201
|
+
check(state.control === "automatic", "manual_control");
|
|
202
|
+
if (profile) check(state.profile === profile && this.turn?.profile === profile, "wrong_profile");
|
|
203
|
+
if (state.profile) check(samePair(this.observed(), this.profilePair(state.profile)), "configuration_mismatch");
|
|
204
|
+
}
|
|
205
|
+
configuredProfilePair(profile) {
|
|
206
|
+
const configured = this.capability?.profiles[profile];
|
|
207
|
+
check(configured, "profile_missing");
|
|
208
|
+
return pairFromProfile(configured);
|
|
209
|
+
}
|
|
210
|
+
profilePair(profile) {
|
|
211
|
+
return this.stateData().profileOverrides.get(profile) ?? this.configuredProfilePair(profile);
|
|
212
|
+
}
|
|
213
|
+
profilePairs(profiles = this.requiredProfiles()) {
|
|
214
|
+
return Object.fromEntries(profiles.map((profile) => [profile, this.profilePair(profile)]));
|
|
215
|
+
}
|
|
216
|
+
workerBasis(state, assignmentId) {
|
|
217
|
+
const recovery = state.recoveryId ? state.recoveries.get(state.recoveryId) : undefined;
|
|
218
|
+
if (recovery?.state === "reading") return state.handoffs.get(recovery.requestHandoffId)?.basisUserEntryId ?? null;
|
|
219
|
+
return this.taskBasis(state, assignmentId);
|
|
220
|
+
}
|
|
221
|
+
}
|