@hassangameryt/freeflow 0.7.2 → 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 +151 -136
- package/capabilities/cognitive-routing/SKILL.md +110 -96
- 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 +40 -21
- 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/cognitive-routing/event-store.js +280 -0
- 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/projection.js +503 -0
- package/pi-extension/dist/cognitive-routing/provenance.js +81 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +31 -10
- package/pi-extension/dist/cognitive-routing/runtime.js +396 -0
- package/pi-extension/dist/cognitive-routing/schemas.js +209 -0
- package/pi-extension/dist/cognitive-routing/session.js +221 -0
- package/pi-extension/dist/cognitive-routing/sources.js +291 -0
- package/pi-extension/dist/cognitive-routing/state.js +487 -0
- package/pi-extension/dist/cognitive-routing/status.js +80 -0
- package/pi-extension/dist/cognitive-routing/tools.js +60 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +10 -12
- 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/host/request-history.js +298 -0
- package/pi-extension/dist/host/runtime-state.js +189 -0
- package/pi-extension/dist/host/settings/freeflow-command.js +1570 -0
- 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 +441 -170
- 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 +45 -0
- package/pi-extension/dist/provider-support/openai/adapter.js +127 -0
- package/pi-extension/dist/provider-support/openai/history.js +127 -0
- package/pi-extension/dist/provider-support/openai/index.js +15 -0
- package/pi-extension/dist/provider-support/openai/session-state.js +105 -0
- 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 +4 -4
- 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 +37 -13
- 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/projection.js +0 -321
- package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -1585
- package/pi-extension/dist/cognitive-routing-v2/schemas.js +0 -107
- package/pi-extension/dist/cognitive-routing-v2/state.js +0 -612
- package/pi-extension/dist/cognitive-routing-v2/tools.js +0 -91
- 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 -356
- 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 -313
- 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 -735
- package/pi-extension/dist/runtime/runtime-identity.js +0 -5
- package/pi-extension/dist/session-sources/events.js +0 -195
- package/pi-extension/dist/session-sources/sources.js +0 -233
- package/pi-extension/dist/settings/settings-ui.js +0 -1160
- 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 -143
- package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -365
- package/pi-extension/src/cognitive-routing-v2/render.ts +0 -256
- package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -1634
- package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -109
- package/pi-extension/src/cognitive-routing-v2/state.ts +0 -622
- package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -93
- package/pi-extension/src/cognitive-routing-v2/types.ts +0 -222
- 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 -406
- 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 -365
- 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 -368
- package/pi-extension/src/integrations/mcp-config.ts +0 -32
- package/pi-extension/src/runtime/runtime-context.ts +0 -838
- package/pi-extension/src/runtime/runtime-identity.ts +0 -8
- package/pi-extension/src/session-sources/events.ts +0 -208
- package/pi-extension/src/session-sources/read-only-session.ts +0 -170
- package/pi-extension/src/session-sources/sources.ts +0 -263
- package/pi-extension/src/settings/settings-tui.ts +0 -501
- package/pi-extension/src/settings/settings-ui.ts +0 -1422
- package/pi-extension/src/ui/text-component.ts +0 -66
- package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -484
- package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
- package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -441
- package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
- package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -245
- package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
- package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -236
- package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -230
- package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -153
- package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
- package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -275
- package/pi-extension/tests/context-virtualization/extension.test.js +0 -765
- package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
- package/pi-extension/tests/context-virtualization/runtime.test.js +0 -216
- 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 -188
- package/pi-extension/tests/integration/mode-free-core.test.js +0 -219
- package/pi-extension/tests/integration/pi-extension.test.js +0 -968
- package/pi-extension/tests/integration/prompt-architecture.test.js +0 -431
- package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
- 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
|
@@ -1,1585 +0,0 @@
|
|
|
1
|
-
import { schemaForProfile } from "./schemas.js";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { EventStore } from "../session-sources/events.js";
|
|
4
|
-
import { Sources, bodyHash, isTaskEvidence } from "../session-sources/sources.js";
|
|
5
|
-
import { pairFromProfile } from "./config.js";
|
|
6
|
-
import { prepareView, changeSelection, representationProblems } from "./projection.js";
|
|
7
|
-
import { initialState } from "./state.js";
|
|
8
|
-
import {
|
|
9
|
-
ROUTING_MESSAGE,
|
|
10
|
-
PROFILES,
|
|
11
|
-
RoutingError,
|
|
12
|
-
canonical,
|
|
13
|
-
emptySelection,
|
|
14
|
-
requireCondition as check,
|
|
15
|
-
samePair,
|
|
16
|
-
} from "./types.js";
|
|
17
|
-
export const ROUTING_TOOLS = ["freeflow_delegate", "freeflow_return", "freeflow_unit", "freeflow_project"];
|
|
18
|
-
const HANDOFF_TOOLS = new Set(["freeflow_delegate", "freeflow_return"]);
|
|
19
|
-
export class RoutingRuntime {
|
|
20
|
-
pi;
|
|
21
|
-
store;
|
|
22
|
-
ctx;
|
|
23
|
-
capability;
|
|
24
|
-
token = randomUUID();
|
|
25
|
-
turn;
|
|
26
|
-
messages = [];
|
|
27
|
-
error;
|
|
28
|
-
projectionError;
|
|
29
|
-
suppressed = false;
|
|
30
|
-
applying;
|
|
31
|
-
externalChange = false;
|
|
32
|
-
targetSignature;
|
|
33
|
-
operations = Promise.resolve();
|
|
34
|
-
revision = 0;
|
|
35
|
-
receipts = new Map();
|
|
36
|
-
pages = new Map();
|
|
37
|
-
manualHold;
|
|
38
|
-
automaticControl = false;
|
|
39
|
-
sourceCache;
|
|
40
|
-
constructor(pi) {
|
|
41
|
-
this.pi = pi;
|
|
42
|
-
}
|
|
43
|
-
subject() {
|
|
44
|
-
const branch = this.store?.reader.getBranch() ?? [];
|
|
45
|
-
return {
|
|
46
|
-
token: this.token,
|
|
47
|
-
revision: this.revision,
|
|
48
|
-
store: this.store,
|
|
49
|
-
leafId: branch.at(-1)?.id ?? null,
|
|
50
|
-
userId: branch.filter((e) => e.message?.role === "user").at(-1)?.id ?? null,
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
current(s) {
|
|
54
|
-
if (s.token !== this.token || s.revision !== this.revision || s.store !== this.store) return false;
|
|
55
|
-
const branch = this.store?.reader.getBranch() ?? [];
|
|
56
|
-
return (
|
|
57
|
-
(!s.leafId || branch.some((e) => e.id === s.leafId)) &&
|
|
58
|
-
(branch.filter((e) => e.message?.role === "user").at(-1)?.id ?? null) === s.userId
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
guard(s) {
|
|
62
|
-
check(
|
|
63
|
-
this.current(s),
|
|
64
|
-
"stale_operation",
|
|
65
|
-
"Routing state changed while the operation was waiting; no further effects applied.",
|
|
66
|
-
);
|
|
67
|
-
}
|
|
68
|
-
taskBasis(state, assignmentId) {
|
|
69
|
-
return state.resumeBasis.has(assignmentId)
|
|
70
|
-
? state.resumeBasis.get(assignmentId)
|
|
71
|
-
: state.assignments.get(assignmentId)?.basisUserEntryId;
|
|
72
|
-
}
|
|
73
|
-
retireUnbound(reason) {
|
|
74
|
-
for (const execution of this.stateData().executions.values()) {
|
|
75
|
-
if (!execution.assistantEntryId && !execution.interrupted)
|
|
76
|
-
this.append({ type: "execution-interrupted", executionId: execution.id, reason });
|
|
77
|
-
}
|
|
78
|
-
this.turn = undefined;
|
|
79
|
-
}
|
|
80
|
-
openTurn() {
|
|
81
|
-
if (!this.turn || this.turn.opened) return;
|
|
82
|
-
const t = this.turn;
|
|
83
|
-
this.append({
|
|
84
|
-
type: "execution-opened",
|
|
85
|
-
execution: {
|
|
86
|
-
id: t.id,
|
|
87
|
-
profile: t.profile,
|
|
88
|
-
assignmentId: t.assignmentId,
|
|
89
|
-
basisUserEntryId: t.basisUserEntryId,
|
|
90
|
-
pair: t.pair,
|
|
91
|
-
resultEntryIds: [],
|
|
92
|
-
},
|
|
93
|
-
});
|
|
94
|
-
t.opened = true;
|
|
95
|
-
}
|
|
96
|
-
async settled(ctx) {
|
|
97
|
-
if (!this.store || !this.supported() || this.store.blocked || !ctx.isIdle?.()) return;
|
|
98
|
-
this.ctx = ctx;
|
|
99
|
-
this.retireUnbound("Native run settled without a complete source binding; prior effects remain unresolved.");
|
|
100
|
-
}
|
|
101
|
-
async beforeRun(ctx) {
|
|
102
|
-
this.ctx = ctx;
|
|
103
|
-
if (!this.store || !this.supported() || this.store.blocked || this.error) return;
|
|
104
|
-
if (this.stateData().control === "automatic" && this.stateData().profile === "executor") {
|
|
105
|
-
const result = await this.control("coordinator", false);
|
|
106
|
-
check(result.status !== "blocked", "reconciliation_required", result.reason);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
stateData() {
|
|
110
|
-
return this.store?.state() ?? initialState();
|
|
111
|
-
}
|
|
112
|
-
sources(state = this.stateData()) {
|
|
113
|
-
const entries = this.ctx.sessionManager
|
|
114
|
-
.getBranch()
|
|
115
|
-
.filter((e) => ["message", "custom_message", "compaction", "branch_summary"].includes(e.type));
|
|
116
|
-
const cache = this.sourceCache;
|
|
117
|
-
if (
|
|
118
|
-
cache &&
|
|
119
|
-
cache.authors === state.authors.size &&
|
|
120
|
-
entries.length === cache.entries.length &&
|
|
121
|
-
entries.every((e, i) => e === cache.entries[i])
|
|
122
|
-
)
|
|
123
|
-
return cache.source;
|
|
124
|
-
const active = this.ctx.sessionManager.buildContextEntries?.();
|
|
125
|
-
const activeIds = active ? new Set(active.map((e) => e.id)) : undefined;
|
|
126
|
-
const source = cache?.source ?? new Sources([], state);
|
|
127
|
-
source.refresh(entries, state, activeIds);
|
|
128
|
-
this.sourceCache = { entries, authors: state.authors.size, source };
|
|
129
|
-
return source;
|
|
130
|
-
}
|
|
131
|
-
observed(ctx = this.ctx) {
|
|
132
|
-
return ctx?.model?.provider && ctx?.model?.id && ctx?.thinkingLevel
|
|
133
|
-
? { provider: ctx.model.provider, modelId: ctx.model.id, thinking: ctx.thinkingLevel }
|
|
134
|
-
: undefined;
|
|
135
|
-
}
|
|
136
|
-
supported() {
|
|
137
|
-
return !!this.capability?.effective && !this.suppressed;
|
|
138
|
-
}
|
|
139
|
-
state() {
|
|
140
|
-
let state;
|
|
141
|
-
try {
|
|
142
|
-
state = this.stateData();
|
|
143
|
-
} catch {
|
|
144
|
-
state = initialState();
|
|
145
|
-
}
|
|
146
|
-
const blocked = this.error ?? this.store?.blocked;
|
|
147
|
-
return {
|
|
148
|
-
effective: this.supported() && state.control !== "inactive" && !blocked,
|
|
149
|
-
activeProfile: state.profile,
|
|
150
|
-
controlMode: state.control === "manual" ? `manual-${state.profile}` : state.control,
|
|
151
|
-
runtimeStatus: blocked ? "blocked" : this.supported() && state.control !== "inactive" ? "active" : "inactive",
|
|
152
|
-
runtimeReason: blocked ?? (this.suppressed ? "startup_selection" : this.capability?.blockingReason.message),
|
|
153
|
-
projectionFailure: this.projectionError,
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
get projectionEnabled() {
|
|
157
|
-
return this.supported() && this.capability?.projection === true && this.stateData().control === "automatic";
|
|
158
|
-
}
|
|
159
|
-
append(data, op, step) {
|
|
160
|
-
check(this.store, "routing_unavailable");
|
|
161
|
-
return this.store.append(this.store.make(data, op, step));
|
|
162
|
-
}
|
|
163
|
-
enqueue(action) {
|
|
164
|
-
const token = this.token;
|
|
165
|
-
const result = this.operations.then(() => {
|
|
166
|
-
check(token === this.token, "stale_instance");
|
|
167
|
-
return action();
|
|
168
|
-
});
|
|
169
|
-
this.operations = result.catch(() => {});
|
|
170
|
-
return result;
|
|
171
|
-
}
|
|
172
|
-
mark(error) {
|
|
173
|
-
if (this.error && error instanceof RoutingError && error.code === "routing_blocked") return;
|
|
174
|
-
this.error =
|
|
175
|
-
error instanceof RoutingError
|
|
176
|
-
? `${error.code}: ${error.message}`
|
|
177
|
-
: error instanceof Error
|
|
178
|
-
? error.message
|
|
179
|
-
: String(error);
|
|
180
|
-
}
|
|
181
|
-
assertAvailable(profile) {
|
|
182
|
-
check(
|
|
183
|
-
this.supported() && this.store && !this.error && !this.store.blocked,
|
|
184
|
-
"routing_unavailable",
|
|
185
|
-
this.error ?? this.store?.blocked ?? "Routing is inactive.",
|
|
186
|
-
);
|
|
187
|
-
const state = this.stateData();
|
|
188
|
-
check(state.control === "automatic", "manual_control");
|
|
189
|
-
if (profile) check(state.profile === profile && this.turn?.profile === profile, "wrong_profile");
|
|
190
|
-
if (state.profile) check(samePair(this.observed(), this.profilePair(state.profile)), "configuration_mismatch");
|
|
191
|
-
}
|
|
192
|
-
profilePair(profile) {
|
|
193
|
-
const configured = this.capability?.profiles[profile];
|
|
194
|
-
check(configured, "profile_missing");
|
|
195
|
-
return pairFromProfile(configured);
|
|
196
|
-
}
|
|
197
|
-
model(profile) {
|
|
198
|
-
const pair = this.profilePair(profile);
|
|
199
|
-
const model = this.ctx?.modelRegistry?.find(pair.provider, pair.modelId);
|
|
200
|
-
check(model, "profile_unavailable");
|
|
201
|
-
return model;
|
|
202
|
-
}
|
|
203
|
-
async bind(ctx, capability, startup = false) {
|
|
204
|
-
this.token = randomUUID();
|
|
205
|
-
this.ctx = ctx;
|
|
206
|
-
this.capability = capability;
|
|
207
|
-
this.turn = undefined;
|
|
208
|
-
this.messages = [];
|
|
209
|
-
this.sourceCache = undefined;
|
|
210
|
-
this.receipts.clear();
|
|
211
|
-
this.pages.clear();
|
|
212
|
-
this.applying = undefined;
|
|
213
|
-
this.externalChange = false;
|
|
214
|
-
this.error = undefined;
|
|
215
|
-
this.projectionError = undefined;
|
|
216
|
-
this.operations = Promise.resolve();
|
|
217
|
-
this.targetSignature = canonical(capability.profiles);
|
|
218
|
-
this.suppressed = startup && process.argv.some((a) => /^(--model|--thinking)(=|$)/.test(a));
|
|
219
|
-
this.store = new EventStore(this.pi, ctx.sessionManager);
|
|
220
|
-
const subject = this.subject();
|
|
221
|
-
if (!capability.effective || this.suppressed) return;
|
|
222
|
-
try {
|
|
223
|
-
await this.store.reconcile();
|
|
224
|
-
this.guard(subject);
|
|
225
|
-
const state = this.stateData();
|
|
226
|
-
this.manualHold = state.control === "manual" ? state.profile : undefined;
|
|
227
|
-
this.automaticControl = !state.events.size || state.control === "automatic";
|
|
228
|
-
this.retireUnbound("Session rebind found an unfinished execution; no task effects replayed.");
|
|
229
|
-
if (!state.events.size) {
|
|
230
|
-
this.append({
|
|
231
|
-
type: "control",
|
|
232
|
-
control: "automatic",
|
|
233
|
-
profile: "coordinator",
|
|
234
|
-
reason: "Initial routing activation",
|
|
235
|
-
});
|
|
236
|
-
await this.applyPair(this.profilePair("coordinator"));
|
|
237
|
-
} else if (
|
|
238
|
-
state.control === "automatic" &&
|
|
239
|
-
state.profile &&
|
|
240
|
-
!samePair(this.observed(), this.profilePair(state.profile))
|
|
241
|
-
) {
|
|
242
|
-
// Reload reconstructs responsibility; it does not silently reapply the last setter.
|
|
243
|
-
this.append({
|
|
244
|
-
type: "control",
|
|
245
|
-
control: "automatic",
|
|
246
|
-
profile: "coordinator",
|
|
247
|
-
reason: "Rebind reconciles historical responsibility with current host control",
|
|
248
|
-
});
|
|
249
|
-
await this.applyPair(this.profilePair("coordinator"));
|
|
250
|
-
}
|
|
251
|
-
} catch (error) {
|
|
252
|
-
if (this.current(subject)) this.mark(error);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
unbind() {
|
|
256
|
-
this.token = randomUUID();
|
|
257
|
-
this.store = undefined;
|
|
258
|
-
this.turn = undefined;
|
|
259
|
-
this.messages = [];
|
|
260
|
-
this.ctx = undefined;
|
|
261
|
-
this.sourceCache = undefined;
|
|
262
|
-
this.receipts.clear();
|
|
263
|
-
this.pages.clear();
|
|
264
|
-
}
|
|
265
|
-
async refresh(ctx, capability) {
|
|
266
|
-
this.ctx = ctx;
|
|
267
|
-
const was = this.capability?.effective === true;
|
|
268
|
-
const signature = canonical(capability.profiles);
|
|
269
|
-
if (this.capability && (was !== capability.effective || signature !== this.targetSignature)) this.revision++;
|
|
270
|
-
this.capability = capability;
|
|
271
|
-
if (!capability.effective) {
|
|
272
|
-
this.turn = undefined;
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
if (!this.store) {
|
|
276
|
-
await this.bind(ctx, capability);
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
if (!was) {
|
|
280
|
-
const subject = this.subject();
|
|
281
|
-
this.suppressed = false;
|
|
282
|
-
try {
|
|
283
|
-
await this.store.reconcile();
|
|
284
|
-
this.guard(subject);
|
|
285
|
-
this.error = undefined;
|
|
286
|
-
this.append({
|
|
287
|
-
type: "control",
|
|
288
|
-
control: "automatic",
|
|
289
|
-
profile: "coordinator",
|
|
290
|
-
reason: "Capability re-enabled; Coordinator reconciliation",
|
|
291
|
-
});
|
|
292
|
-
this.automaticControl = true;
|
|
293
|
-
await this.applyPair(this.profilePair("coordinator"));
|
|
294
|
-
} catch (error) {
|
|
295
|
-
if (this.current(subject)) this.mark(error);
|
|
296
|
-
}
|
|
297
|
-
} else if (this.targetSignature && signature !== this.targetSignature) {
|
|
298
|
-
this.error = "configuration_changed: reconcile profile configuration before automatic execution";
|
|
299
|
-
}
|
|
300
|
-
if (canonical(this.capability?.profiles) === signature) this.targetSignature = signature;
|
|
301
|
-
}
|
|
302
|
-
async ancestryChanged(ctx, navigation = true) {
|
|
303
|
-
this.revision++;
|
|
304
|
-
this.ctx = ctx;
|
|
305
|
-
this.turn = undefined;
|
|
306
|
-
this.messages = [];
|
|
307
|
-
this.sourceCache = undefined;
|
|
308
|
-
this.receipts.clear();
|
|
309
|
-
this.pages.clear();
|
|
310
|
-
if (!this.store || !this.supported()) return;
|
|
311
|
-
const subject = this.subject();
|
|
312
|
-
try {
|
|
313
|
-
await this.store.reconcile();
|
|
314
|
-
this.guard(subject);
|
|
315
|
-
this.error = undefined;
|
|
316
|
-
this.retireUnbound("Selected historical ancestry ends before execution binding; effects are not replayed.");
|
|
317
|
-
const state = this.stateData();
|
|
318
|
-
if (this.manualHold) {
|
|
319
|
-
this.append({
|
|
320
|
-
type: "control",
|
|
321
|
-
control: "manual",
|
|
322
|
-
profile: this.manualHold,
|
|
323
|
-
reason: "Current explicit manual hold survives navigation",
|
|
324
|
-
});
|
|
325
|
-
} else if (
|
|
326
|
-
(this.automaticControl || !state.events.size) &&
|
|
327
|
-
(navigation || !samePair(this.observed(), this.profilePair(state.profile ?? "coordinator")))
|
|
328
|
-
) {
|
|
329
|
-
this.append({
|
|
330
|
-
type: "control",
|
|
331
|
-
control: "automatic",
|
|
332
|
-
profile: "coordinator",
|
|
333
|
-
reason: "Coordinator reconciles selected native ancestry",
|
|
334
|
-
});
|
|
335
|
-
await this.applyPair(this.profilePair("coordinator"));
|
|
336
|
-
}
|
|
337
|
-
} catch (error) {
|
|
338
|
-
if (this.current(subject)) this.mark(error);
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
async nativeChange(ctx) {
|
|
342
|
-
this.ctx = ctx;
|
|
343
|
-
if (!this.supported() || !this.store) return;
|
|
344
|
-
if (this.applying) {
|
|
345
|
-
if (ctx.model?.provider !== this.applying.provider || ctx.model?.id !== this.applying.modelId) {
|
|
346
|
-
this.externalChange = true;
|
|
347
|
-
this.revision++;
|
|
348
|
-
}
|
|
349
|
-
return; // Never await a queue already held by our setter.
|
|
350
|
-
}
|
|
351
|
-
const state = this.stateData();
|
|
352
|
-
if (state.control !== "automatic" || !state.profile || samePair(this.observed(), this.profilePair(state.profile)))
|
|
353
|
-
return;
|
|
354
|
-
try {
|
|
355
|
-
this.revision++;
|
|
356
|
-
this.manualHold = undefined;
|
|
357
|
-
this.automaticControl = false;
|
|
358
|
-
this.append({ type: "control", control: "inactive", reason: "External native model/effort change" });
|
|
359
|
-
} catch (error) {
|
|
360
|
-
this.mark(error);
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
async applyPair(target) {
|
|
364
|
-
const subject = this.subject(),
|
|
365
|
-
token = this.token,
|
|
366
|
-
prior = this.observed();
|
|
367
|
-
if (samePair(prior, target)) return;
|
|
368
|
-
const model = this.ctx.modelRegistry.find(target.provider, target.modelId);
|
|
369
|
-
check(model, "profile_unavailable");
|
|
370
|
-
const auth = await this.ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
371
|
-
this.guard(subject);
|
|
372
|
-
check(auth?.ok, "profile_unauthenticated");
|
|
373
|
-
this.applying = target;
|
|
374
|
-
let ownedPair = target;
|
|
375
|
-
this.externalChange = false;
|
|
376
|
-
try {
|
|
377
|
-
check(await this.pi.setModel(model), "model_rejected");
|
|
378
|
-
this.guard(subject);
|
|
379
|
-
this.pi.setThinkingLevel(target.thinking);
|
|
380
|
-
check(!this.externalChange && samePair(this.observed(), target), "configuration_mismatch");
|
|
381
|
-
} catch (error) {
|
|
382
|
-
if (this.current(subject) && prior && !this.externalChange) {
|
|
383
|
-
const old = this.ctx.modelRegistry.find(prior.provider, prior.modelId);
|
|
384
|
-
try {
|
|
385
|
-
this.applying = prior;
|
|
386
|
-
ownedPair = prior;
|
|
387
|
-
check(old && (await this.pi.setModel(old)), "rollback_failed");
|
|
388
|
-
this.guard(subject);
|
|
389
|
-
this.pi.setThinkingLevel(prior.thinking);
|
|
390
|
-
check(samePair(this.observed(), prior), "rollback_failed");
|
|
391
|
-
} catch {
|
|
392
|
-
if (this.current(subject)) this.error = "configuration_unknown: rollback could not be observed";
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
throw error;
|
|
396
|
-
} finally {
|
|
397
|
-
if (token === this.token && this.applying === ownedPair) this.applying = undefined;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
async control(profile, manual) {
|
|
401
|
-
this.revision++;
|
|
402
|
-
const subject = this.subject();
|
|
403
|
-
return this.enqueue(async () => {
|
|
404
|
-
try {
|
|
405
|
-
check(this.capability?.effective && this.store, "routing_unavailable");
|
|
406
|
-
await this.store.reconcile();
|
|
407
|
-
this.guard(subject);
|
|
408
|
-
this.error = undefined;
|
|
409
|
-
this.suppressed = false;
|
|
410
|
-
const previous = this.stateData();
|
|
411
|
-
if (
|
|
412
|
-
previous.control === (manual ? "manual" : "automatic") &&
|
|
413
|
-
previous.profile === profile &&
|
|
414
|
-
samePair(this.observed(), this.profilePair(profile))
|
|
415
|
-
) {
|
|
416
|
-
this.manualHold = manual ? profile : undefined;
|
|
417
|
-
this.automaticControl = !manual;
|
|
418
|
-
return { status: manual ? "active" : "automatic" };
|
|
419
|
-
}
|
|
420
|
-
this.append({
|
|
421
|
-
type: "control",
|
|
422
|
-
control: manual ? "manual" : "automatic",
|
|
423
|
-
profile,
|
|
424
|
-
reason: manual ? "Explicit user manual hold" : "Explicit user automatic release/reconciliation",
|
|
425
|
-
});
|
|
426
|
-
try {
|
|
427
|
-
await this.applyPair(this.profilePair(profile));
|
|
428
|
-
this.guard(subject);
|
|
429
|
-
} catch (error) {
|
|
430
|
-
if (this.current(subject) && !this.error && !this.store.blocked)
|
|
431
|
-
this.append({
|
|
432
|
-
type: "control",
|
|
433
|
-
control: previous.control,
|
|
434
|
-
profile: previous.profile,
|
|
435
|
-
reason: "Control request failed; prior control retained",
|
|
436
|
-
});
|
|
437
|
-
throw error;
|
|
438
|
-
}
|
|
439
|
-
this.manualHold = manual ? profile : undefined;
|
|
440
|
-
this.automaticControl = !manual;
|
|
441
|
-
return { status: manual ? "active" : "automatic" };
|
|
442
|
-
} catch (error) {
|
|
443
|
-
if (this.current(subject)) this.mark(error);
|
|
444
|
-
return { status: "blocked", reason: error instanceof Error ? error.message : String(error) };
|
|
445
|
-
}
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
setManualProfile(profile, _mechanism) {
|
|
449
|
-
return this.control(profile, true);
|
|
450
|
-
}
|
|
451
|
-
setAutomaticControl(_mechanism) {
|
|
452
|
-
return this.control("coordinator", false);
|
|
453
|
-
}
|
|
454
|
-
lastDeliveredUser(sources, messages) {
|
|
455
|
-
const delivered = new Set(
|
|
456
|
-
sources.associate(messages).flatMap((x) => (x.source?.message.role === "user" ? [x.source.entry.id] : [])),
|
|
457
|
-
);
|
|
458
|
-
// Compaction may remove every user message from the active view. Retain
|
|
459
|
-
// observed delivery on this ancestry; a stored but undelivered user entry
|
|
460
|
-
// must not advance the basis, and absence must not manufacture new input.
|
|
461
|
-
for (const execution of this.stateData().executions.values())
|
|
462
|
-
if (execution.basisUserEntryId) delivered.add(execution.basisUserEntryId);
|
|
463
|
-
for (let i = sources.entries.length - 1; i >= 0; i--) {
|
|
464
|
-
const entry = sources.entries[i];
|
|
465
|
-
if (entry.message?.role === "user" && delivered.has(entry.id)) return entry.id;
|
|
466
|
-
}
|
|
467
|
-
return null;
|
|
468
|
-
}
|
|
469
|
-
runtimeMessage(state, attention = false) {
|
|
470
|
-
const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
471
|
-
const h = state.pendingId
|
|
472
|
-
? state.handoffs.get(state.pendingId)
|
|
473
|
-
: state.assessment
|
|
474
|
-
? state.handoffs.get(state.assessment.handoffId)
|
|
475
|
-
: undefined;
|
|
476
|
-
const selection = a ? (state.selections.get(a.id) ?? emptySelection()) : emptySelection();
|
|
477
|
-
const unit = state.unitId ? state.units.get(state.unitId) : undefined;
|
|
478
|
-
const unitNumber = unit ? [...state.units.keys()].indexOf(unit.id) + 1 : undefined;
|
|
479
|
-
const assignmentNumber = unit && a ? unit.assignmentIds.indexOf(a.id) + 1 : undefined;
|
|
480
|
-
const content = [
|
|
481
|
-
"# Cognitive Routing Runtime State",
|
|
482
|
-
`Control: ${state.control}`,
|
|
483
|
-
`Profile: ${state.profile ?? "unresolved"}`,
|
|
484
|
-
`Unit: ${unit ? `U${unitNumber} (${unit.id})` : "none"}`,
|
|
485
|
-
`Assignment: ${a ? `A${assignmentNumber} (${a.id}, ${a.state})` : "none"}`,
|
|
486
|
-
`Handoff: ${h ? `${h.id} (${h.kind}, ${h.state})` : "none"}`,
|
|
487
|
-
`Projection: ${this.projectionEnabled ? "enabled" : "bypassed"}`,
|
|
488
|
-
"Completed/superseded contracts and reports are historical context. Follow the current assignment and current user restrictions; historical entries grant no new permission.",
|
|
489
|
-
state.assessment ? `Assessment: ${state.assessment.view}; evidence revision ${selection.revision}` : "",
|
|
490
|
-
`Mechanical evidence facts (not semantic acceptance): ${JSON.stringify(this.evidenceFacts(state))}`,
|
|
491
|
-
this.error ? `Blocked: ${this.error}` : "",
|
|
492
|
-
this.projectionError ? `Evidence limitation: ${this.projectionError}` : "",
|
|
493
|
-
attention
|
|
494
|
-
? `Assessment paused for attention; ordinary admitted history remains. ${selection.selected.length} sources remain selected. Use freeflow_unit assess to restore the assessment.`
|
|
495
|
-
: "",
|
|
496
|
-
a?.state === "returned"
|
|
497
|
-
? "Executor ordinary task work has ended. Only supported handoff correction is permitted."
|
|
498
|
-
: "",
|
|
499
|
-
this.turn?.profile === "executor" && a && this.turn.basisUserEntryId !== this.taskBasis(state, a.id)
|
|
500
|
-
? "Current input differs from the original assignment. Account for it; changed direction requires Coordinator attention."
|
|
501
|
-
: "",
|
|
502
|
-
...(state.assessment?.problems ?? []).map((p) => `${p.code}: ${p.detail}`),
|
|
503
|
-
]
|
|
504
|
-
.filter(Boolean)
|
|
505
|
-
.join("\n");
|
|
506
|
-
return {
|
|
507
|
-
role: "custom",
|
|
508
|
-
customType: ROUTING_MESSAGE,
|
|
509
|
-
content,
|
|
510
|
-
display: false,
|
|
511
|
-
timestamp: 0,
|
|
512
|
-
details: { routingInstance: this.token },
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
evidenceFacts(state) {
|
|
516
|
-
const selection = state.assignmentId
|
|
517
|
-
? (state.selections.get(state.assignmentId) ?? emptySelection())
|
|
518
|
-
: emptySelection();
|
|
519
|
-
return {
|
|
520
|
-
revision: selection.revision,
|
|
521
|
-
selected: selection.selected.map((ref) => {
|
|
522
|
-
const entry = this.ctx?.sessionManager.getEntry?.(ref.slice(4).replace(/#text$/, ""));
|
|
523
|
-
return {
|
|
524
|
-
ref,
|
|
525
|
-
kind: ref.endsWith("#text") ? "assistant-text" : (entry?.message?.role ?? "unknown"),
|
|
526
|
-
toolName: entry?.message?.toolName,
|
|
527
|
-
producer: state.authors.get(entry?.id)?.profile ?? "common",
|
|
528
|
-
assignment: state.authors.get(entry?.id)?.assignmentId,
|
|
529
|
-
};
|
|
530
|
-
}),
|
|
531
|
-
unresolved: selection.unresolved,
|
|
532
|
-
withdrawals: selection.withdrawals,
|
|
533
|
-
preparedRevision: state.assessment?.reservation?.selectionRevision,
|
|
534
|
-
limitations: state.assessment?.problems ?? [],
|
|
535
|
-
};
|
|
536
|
-
}
|
|
537
|
-
prepared(profile, input, handoffId, restoring = false) {
|
|
538
|
-
const state = this.stateData(),
|
|
539
|
-
model = this.model(profile);
|
|
540
|
-
return prepareView({
|
|
541
|
-
messages: input,
|
|
542
|
-
sources: this.sources(state),
|
|
543
|
-
state,
|
|
544
|
-
view: profile,
|
|
545
|
-
projection: this.projectionEnabled,
|
|
546
|
-
model,
|
|
547
|
-
pair: this.profilePair(profile),
|
|
548
|
-
systemPrompt: this.ctx.getSystemPrompt?.() ?? "",
|
|
549
|
-
tools: (this.pi.getAllTools?.() ?? [])
|
|
550
|
-
.filter((tool) =>
|
|
551
|
-
ROUTING_TOOLS.includes(tool.name)
|
|
552
|
-
? tool.name === "freeflow_unit" ||
|
|
553
|
-
(profile === "coordinator"
|
|
554
|
-
? tool.name === "freeflow_delegate"
|
|
555
|
-
: tool.name === "freeflow_return" || (tool.name === "freeflow_project" && this.projectionEnabled))
|
|
556
|
-
: this.pi.getActiveTools?.().includes(tool.name),
|
|
557
|
-
)
|
|
558
|
-
.map((tool) =>
|
|
559
|
-
ROUTING_TOOLS.includes(tool.name)
|
|
560
|
-
? { ...tool, parameters: schemaForProfile(tool.name, profile === "coordinator") }
|
|
561
|
-
: tool,
|
|
562
|
-
),
|
|
563
|
-
runtimeMessage: this.runtimeMessage(
|
|
564
|
-
state,
|
|
565
|
-
profile === "coordinator" && state.assessment?.view === "suspended" && !restoring && !handoffId,
|
|
566
|
-
),
|
|
567
|
-
instance: this.token,
|
|
568
|
-
preparingReturn: handoffId,
|
|
569
|
-
restoring,
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
async context(ctx, incoming) {
|
|
573
|
-
this.ctx = ctx;
|
|
574
|
-
const input = incoming.filter(
|
|
575
|
-
(m) =>
|
|
576
|
-
!(
|
|
577
|
-
m?.details?.routingInstance === this.token &&
|
|
578
|
-
[ROUTING_MESSAGE, "freeflow-routing-v2-refs"].includes(m.customType)
|
|
579
|
-
),
|
|
580
|
-
);
|
|
581
|
-
this.messages = input;
|
|
582
|
-
if (!this.supported() || !this.store) return input;
|
|
583
|
-
try {
|
|
584
|
-
const state = this.stateData();
|
|
585
|
-
if (state.control !== "automatic") return input;
|
|
586
|
-
check(!this.error && !this.store.blocked && state.profile, "routing_blocked", this.error ?? this.store.blocked);
|
|
587
|
-
check(samePair(this.observed(), this.profilePair(state.profile)), "prepared_pair_mismatch");
|
|
588
|
-
const sources = this.sources(state),
|
|
589
|
-
user = this.lastDeliveredUser(sources, input);
|
|
590
|
-
if (state.assessment && user && user !== state.assessment.basisUserEntryId)
|
|
591
|
-
this.append(
|
|
592
|
-
{
|
|
593
|
-
type: "assessment-suspended",
|
|
594
|
-
handoffId: state.assessment.handoffId,
|
|
595
|
-
reason: "user-attention",
|
|
596
|
-
basisUserEntryId: user,
|
|
597
|
-
problems: [],
|
|
598
|
-
},
|
|
599
|
-
JSON.stringify(["attention", state.assessment.handoffId, user]),
|
|
600
|
-
);
|
|
601
|
-
// New input reaching an already prepared Executor request cannot be rerouted by changing only the live model.
|
|
602
|
-
const outstanding = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
603
|
-
const interrupted =
|
|
604
|
-
state.profile === "executor" && user !== (outstanding ? this.taskBasis(state, outstanding.id) : undefined);
|
|
605
|
-
if (!this.turn || this.turn.bound) {
|
|
606
|
-
this.receipts.clear();
|
|
607
|
-
const execution = {
|
|
608
|
-
id: randomUUID(),
|
|
609
|
-
profile: state.profile,
|
|
610
|
-
assignmentId: state.assignmentId,
|
|
611
|
-
basisUserEntryId: user,
|
|
612
|
-
pair: this.observed(),
|
|
613
|
-
resultEntryIds: [],
|
|
614
|
-
};
|
|
615
|
-
const before = new Set(ctx.sessionManager.getBranch().map((e) => e.id));
|
|
616
|
-
this.turn = {
|
|
617
|
-
id: execution.id,
|
|
618
|
-
profile: execution.profile,
|
|
619
|
-
assignmentId: execution.assignmentId,
|
|
620
|
-
basisUserEntryId: user,
|
|
621
|
-
before,
|
|
622
|
-
pair: execution.pair,
|
|
623
|
-
};
|
|
624
|
-
this.openTurn();
|
|
625
|
-
}
|
|
626
|
-
let prepared = this.prepared(state.profile, input);
|
|
627
|
-
if (!prepared.ready && state.profile === "coordinator" && this.stateData().assessment) {
|
|
628
|
-
const assessment = this.stateData().assessment;
|
|
629
|
-
this.append({
|
|
630
|
-
type: "assessment-suspended",
|
|
631
|
-
handoffId: assessment.handoffId,
|
|
632
|
-
reason: "delivery-gap",
|
|
633
|
-
basisUserEntryId: user,
|
|
634
|
-
problems: prepared.problems,
|
|
635
|
-
});
|
|
636
|
-
this.projectionError = prepared.problems.map((p) => p.code).join(", ");
|
|
637
|
-
prepared = this.prepared("coordinator", input);
|
|
638
|
-
}
|
|
639
|
-
check(prepared.ready, "context_unavailable", prepared.problems.map((p) => p.detail).join("; "));
|
|
640
|
-
const known = this.stateData().exposure;
|
|
641
|
-
const added = prepared.fullSources.filter((s) => known.get(s.ref) !== s.hash);
|
|
642
|
-
if (this.turn.profile === "executor")
|
|
643
|
-
for (let i = 0; i < added.length; i += 128)
|
|
644
|
-
this.append({
|
|
645
|
-
type: "sources-exposed",
|
|
646
|
-
executionId: this.turn.id,
|
|
647
|
-
view: "executor",
|
|
648
|
-
sources: added.slice(i, i + 128).map((s) => ({ ref: s.ref, bodyHash: s.hash })),
|
|
649
|
-
});
|
|
650
|
-
if (interrupted)
|
|
651
|
-
prepared.messages.push({
|
|
652
|
-
role: "custom",
|
|
653
|
-
customType: ROUTING_MESSAGE,
|
|
654
|
-
display: false,
|
|
655
|
-
timestamp: 0,
|
|
656
|
-
details: { routingInstance: this.token },
|
|
657
|
-
content:
|
|
658
|
-
"New delivered user input requires Coordinator attention. Do not run ordinary task tools; return the current partial result.",
|
|
659
|
-
});
|
|
660
|
-
return prepared.messages;
|
|
661
|
-
} catch (error) {
|
|
662
|
-
this.mark(error);
|
|
663
|
-
ctx.abort?.();
|
|
664
|
-
// Do not send an accidental full Executor history on a projection failure.
|
|
665
|
-
return [
|
|
666
|
-
{
|
|
667
|
-
role: "custom",
|
|
668
|
-
customType: ROUTING_MESSAGE,
|
|
669
|
-
content: `Automatic request blocked: ${this.error}`,
|
|
670
|
-
display: false,
|
|
671
|
-
timestamp: 0,
|
|
672
|
-
details: { routingInstance: this.token },
|
|
673
|
-
},
|
|
674
|
-
];
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
messageEnd(message) {
|
|
678
|
-
if (message?.role === "assistant" && this.turn && !this.turn.bound) this.turn.message = structuredClone(message);
|
|
679
|
-
}
|
|
680
|
-
contextOperation(name, input) {
|
|
681
|
-
return name === "freeflow_context" && ["archive", "restore", "search", "retrieve"].includes(input?.operation);
|
|
682
|
-
}
|
|
683
|
-
batch(callId, name) {
|
|
684
|
-
check(this.turn?.message, "batch_unavailable");
|
|
685
|
-
const matches = this.ctx.sessionManager
|
|
686
|
-
.getBranch()
|
|
687
|
-
.filter(
|
|
688
|
-
(e) =>
|
|
689
|
-
!this.turn.before.has(e.id) &&
|
|
690
|
-
e.type === "message" &&
|
|
691
|
-
e.message?.role === "assistant" &&
|
|
692
|
-
e.message.content?.some((b) => b.type === "toolCall" && b.id === callId),
|
|
693
|
-
);
|
|
694
|
-
check(matches.length === 1, "batch_source_changed");
|
|
695
|
-
const fingerprint = bodyHash(matches[0].message);
|
|
696
|
-
check(!this.turn.sourceFingerprint || this.turn.sourceFingerprint === fingerprint, "batch_source_changed");
|
|
697
|
-
// Later message_end handlers may legitimately replace the message. The first
|
|
698
|
-
// preflight freezes the actually persisted batch before any of its tools act.
|
|
699
|
-
this.turn.sourceFingerprint = fingerprint;
|
|
700
|
-
this.turn.message = structuredClone(matches[0].message);
|
|
701
|
-
const calls = (this.turn.message.content ?? []).filter((b) => b.type === "toolCall");
|
|
702
|
-
const handoffs = calls.filter((b) => HANDOFF_TOOLS.has(b.name));
|
|
703
|
-
check(
|
|
704
|
-
!handoffs.length ||
|
|
705
|
-
(handoffs.length === 1 &&
|
|
706
|
-
HANDOFF_TOOLS.has(calls.at(-1)?.name) &&
|
|
707
|
-
calls.every(
|
|
708
|
-
(b) =>
|
|
709
|
-
HANDOFF_TOOLS.has(b.name) || b.name === "freeflow_project" || this.contextOperation(b.name, b.arguments),
|
|
710
|
-
)),
|
|
711
|
-
"invalid_handoff_batch",
|
|
712
|
-
"A handoff must be last and cannot accompany ordinary task tools.",
|
|
713
|
-
);
|
|
714
|
-
check(
|
|
715
|
-
calls.some((b) => b.id === callId && b.name === name),
|
|
716
|
-
"call_not_in_batch",
|
|
717
|
-
);
|
|
718
|
-
}
|
|
719
|
-
preflight(event, ctx) {
|
|
720
|
-
this.ctx = ctx;
|
|
721
|
-
const name = event.toolName,
|
|
722
|
-
isRouting = ROUTING_TOOLS.includes(name);
|
|
723
|
-
if (!this.supported()) return isRouting ? { block: true, reason: "Routing is unavailable." } : undefined;
|
|
724
|
-
try {
|
|
725
|
-
const state = this.stateData();
|
|
726
|
-
if (state.control === "manual")
|
|
727
|
-
return isRouting && name !== "freeflow_unit" ? { block: true, reason: "Manual control is active." } : undefined;
|
|
728
|
-
if (state.control !== "automatic")
|
|
729
|
-
return isRouting ? { block: true, reason: "Automatic routing is inactive." } : undefined;
|
|
730
|
-
this.batch(event.toolCallId, name);
|
|
731
|
-
check(!this.error && !this.store?.blocked, "routing_blocked");
|
|
732
|
-
this.openTurn();
|
|
733
|
-
if (this.turn?.profile === "executor" && !isRouting && !this.contextOperation(name, event.input)) {
|
|
734
|
-
const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
735
|
-
check(
|
|
736
|
-
a?.state === "outstanding" &&
|
|
737
|
-
this.turn.basisUserEntryId === this.taskBasis(state, a.id) &&
|
|
738
|
-
state.profile === "executor",
|
|
739
|
-
"executor_task_phase_ended",
|
|
740
|
-
);
|
|
741
|
-
}
|
|
742
|
-
return undefined;
|
|
743
|
-
} catch (error) {
|
|
744
|
-
return { block: true, reason: error instanceof Error ? error.message : String(error) };
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
callOperation(callId, name) {
|
|
748
|
-
check(this.turn && this.store, "execution_missing");
|
|
749
|
-
this.batch(callId, name);
|
|
750
|
-
return JSON.stringify([this.store.reader.getSessionId(), this.turn.id, callId, name]);
|
|
751
|
-
}
|
|
752
|
-
result(value) {
|
|
753
|
-
return { content: [{ type: "text", text: JSON.stringify(value) }], details: value };
|
|
754
|
-
}
|
|
755
|
-
async invoke(name, callId, input, signal, ctx) {
|
|
756
|
-
return this.enqueue(async () => {
|
|
757
|
-
this.ctx = ctx;
|
|
758
|
-
try {
|
|
759
|
-
check(!signal?.aborted, "cancelled");
|
|
760
|
-
if (name === "freeflow_unit" && input.operation === "inspect") return this.result(this.inspectUnit(input));
|
|
761
|
-
this.assertAvailable(name === "freeflow_delegate" || name === "freeflow_unit" ? "coordinator" : "executor");
|
|
762
|
-
const op = this.callOperation(callId, name);
|
|
763
|
-
const cached = this.receipts.get(op);
|
|
764
|
-
if (cached) {
|
|
765
|
-
check(cached.input === canonical(input), "operation_conflict");
|
|
766
|
-
return this.result(structuredClone(cached.value));
|
|
767
|
-
}
|
|
768
|
-
const value =
|
|
769
|
-
name === "freeflow_delegate"
|
|
770
|
-
? this.delegate(input, callId, op)
|
|
771
|
-
: name === "freeflow_return"
|
|
772
|
-
? this.returnReport(input, callId, op)
|
|
773
|
-
: name === "freeflow_project"
|
|
774
|
-
? this.project(input, op)
|
|
775
|
-
: name === "freeflow_unit"
|
|
776
|
-
? this.unit(input, op)
|
|
777
|
-
: undefined;
|
|
778
|
-
if (value !== undefined) {
|
|
779
|
-
this.receipts.set(op, { input: canonical(input), value: structuredClone(value) });
|
|
780
|
-
return this.result(value);
|
|
781
|
-
}
|
|
782
|
-
throw new RoutingError("unknown_tool", name);
|
|
783
|
-
} catch (error) {
|
|
784
|
-
return this.result({
|
|
785
|
-
status: "blocked",
|
|
786
|
-
code: error instanceof RoutingError ? error.code : "operation_failed",
|
|
787
|
-
message: error instanceof Error ? error.message : String(error),
|
|
788
|
-
problems: error instanceof RoutingError ? error.problems : [],
|
|
789
|
-
observed: this.observed(),
|
|
790
|
-
expectedProfile:
|
|
791
|
-
name === "freeflow_unit" && input.operation === "inspect"
|
|
792
|
-
? undefined
|
|
793
|
-
: name === "freeflow_delegate" || name === "freeflow_unit"
|
|
794
|
-
? "coordinator"
|
|
795
|
-
: "executor",
|
|
796
|
-
recoveryAction:
|
|
797
|
-
error instanceof RoutingError &&
|
|
798
|
-
[
|
|
799
|
-
"cursor_expired",
|
|
800
|
-
"invalid_cursor",
|
|
801
|
-
"work_ref_required",
|
|
802
|
-
"invalid_work_ref",
|
|
803
|
-
"work_unavailable",
|
|
804
|
-
"invalid_inspection",
|
|
805
|
-
].includes(error.code)
|
|
806
|
-
? "Inspect again without a cursor and use a returned work ref. Lookup recovery does not require a new assignment."
|
|
807
|
-
: "Preserve saved work. Use freeflow_unit inspect; reconcile current input/control before retrying the named operation.",
|
|
808
|
-
});
|
|
809
|
-
}
|
|
810
|
-
});
|
|
811
|
-
}
|
|
812
|
-
duplicate(op) {
|
|
813
|
-
return [...this.stateData().events.values()].find(
|
|
814
|
-
(e) =>
|
|
815
|
-
e.operationId === op &&
|
|
816
|
-
["delegate-accepted", "return-accepted", "handoff-retry-requested"].includes(e.data.type),
|
|
817
|
-
);
|
|
818
|
-
}
|
|
819
|
-
delegate(input, callId, op) {
|
|
820
|
-
const prior = this.duplicate(op);
|
|
821
|
-
if (prior) {
|
|
822
|
-
check(
|
|
823
|
-
prior.data.type === "delegate-accepted" && prior.data.assignment.contract === input.contract,
|
|
824
|
-
"operation_conflict",
|
|
825
|
-
);
|
|
826
|
-
return { status: "accepted", handoff: prior.data.handoff.id, unchanged: true };
|
|
827
|
-
}
|
|
828
|
-
const state = this.stateData();
|
|
829
|
-
const unit = state.unitId
|
|
830
|
-
? state.units.get(state.unitId)
|
|
831
|
-
: { id: randomUUID(), objective: input.contract, state: "open", assignmentIds: [] };
|
|
832
|
-
const old = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
833
|
-
if (input.operation === "replace") check(old?.state === "outstanding" && !this.applying, "no_quiescent_assignment");
|
|
834
|
-
else
|
|
835
|
-
check(input.operation === "assign" && old?.state !== "outstanding" && !state.pendingId, "assignment_outstanding");
|
|
836
|
-
const assignmentId = randomUUID(),
|
|
837
|
-
id = randomUUID();
|
|
838
|
-
const assignment = {
|
|
839
|
-
id: assignmentId,
|
|
840
|
-
unitId: unit.id,
|
|
841
|
-
contract: input.contract,
|
|
842
|
-
state: "outstanding",
|
|
843
|
-
delegateHandoffId: id,
|
|
844
|
-
basisUserEntryId: this.turn.basisUserEntryId,
|
|
845
|
-
};
|
|
846
|
-
const h = {
|
|
847
|
-
id,
|
|
848
|
-
kind: "delegate",
|
|
849
|
-
assignmentId,
|
|
850
|
-
text: input.contract,
|
|
851
|
-
from: "coordinator",
|
|
852
|
-
to: "executor",
|
|
853
|
-
executionId: this.turn.id,
|
|
854
|
-
toolCallId: callId,
|
|
855
|
-
basisUserEntryId: this.turn.basisUserEntryId,
|
|
856
|
-
state: "pending",
|
|
857
|
-
reportRevision: 0,
|
|
858
|
-
limitations: [],
|
|
859
|
-
};
|
|
860
|
-
this.append(
|
|
861
|
-
{
|
|
862
|
-
type: "delegate-accepted",
|
|
863
|
-
unit: { ...unit, assignmentIds: [...unit.assignmentIds, assignmentId] },
|
|
864
|
-
assignment,
|
|
865
|
-
handoff: h,
|
|
866
|
-
...(input.operation === "replace"
|
|
867
|
-
? {
|
|
868
|
-
replacement: {
|
|
869
|
-
assignmentId: old.id,
|
|
870
|
-
reason: input.reason,
|
|
871
|
-
...(state.pendingId ? { supersededHandoffId: state.pendingId } : {}),
|
|
872
|
-
},
|
|
873
|
-
}
|
|
874
|
-
: {}),
|
|
875
|
-
},
|
|
876
|
-
op,
|
|
877
|
-
);
|
|
878
|
-
return {
|
|
879
|
-
status: "accepted",
|
|
880
|
-
unit: unit.id,
|
|
881
|
-
assignment: assignmentId,
|
|
882
|
-
handoff: id,
|
|
883
|
-
transition: "pending",
|
|
884
|
-
contract: input.contract,
|
|
885
|
-
reason: input.reason,
|
|
886
|
-
createdUnit: !state.unitId,
|
|
887
|
-
...(old && input.operation === "replace"
|
|
888
|
-
? {
|
|
889
|
-
replacedAssignment: old.id,
|
|
890
|
-
continuity:
|
|
891
|
-
"Prior effects and evidence remain on native history. Reconcile uncertain effects before dependent work.",
|
|
892
|
-
}
|
|
893
|
-
: {}),
|
|
894
|
-
};
|
|
895
|
-
}
|
|
896
|
-
returnReport(input, callId, op) {
|
|
897
|
-
const state = this.stateData(),
|
|
898
|
-
a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
899
|
-
check(a, "assignment_missing");
|
|
900
|
-
const saved = a.returnHandoffId ? state.handoffs.get(a.returnHandoffId) : undefined;
|
|
901
|
-
const selection = state.selections.get(a.id) ?? emptySelection();
|
|
902
|
-
const duplicate = this.duplicate(op);
|
|
903
|
-
if (duplicate) {
|
|
904
|
-
if (input.operation === "retry") check(duplicate.data.type === "handoff-retry-requested", "operation_conflict");
|
|
905
|
-
else
|
|
906
|
-
check(
|
|
907
|
-
duplicate.data.type === "return-accepted" &&
|
|
908
|
-
duplicate.data.handoff.text === input.report &&
|
|
909
|
-
duplicate.data.handoff.outcome === input.outcome &&
|
|
910
|
-
canonical(duplicate.data.handoff.limitations) === canonical(input.limitations ?? []),
|
|
911
|
-
"operation_conflict",
|
|
912
|
-
);
|
|
913
|
-
return {
|
|
914
|
-
status: "accepted",
|
|
915
|
-
reportSaved: true,
|
|
916
|
-
unchanged: true,
|
|
917
|
-
handoff: duplicate.data.handoffId ?? duplicate.data.handoff.id,
|
|
918
|
-
};
|
|
919
|
-
}
|
|
920
|
-
if (input.operation === "retry") {
|
|
921
|
-
check(saved && ["blocked", "pending"].includes(saved.state), "saved_return_missing");
|
|
922
|
-
this.append(
|
|
923
|
-
{
|
|
924
|
-
type: "handoff-retry-requested",
|
|
925
|
-
handoffId: saved.id,
|
|
926
|
-
attemptId: randomUUID(),
|
|
927
|
-
executionId: this.turn.id,
|
|
928
|
-
toolCallId: callId,
|
|
929
|
-
reportRevision: saved.reportRevision,
|
|
930
|
-
selectionRevision: selection.revision,
|
|
931
|
-
},
|
|
932
|
-
op,
|
|
933
|
-
);
|
|
934
|
-
return { ...this.returnReadiness(saved.id), reportUnchanged: true };
|
|
935
|
-
}
|
|
936
|
-
check(input.operation === "submit", "invalid_return_operation");
|
|
937
|
-
check(
|
|
938
|
-
a.state === "outstanding" || (a.state === "returned" && saved && ["pending", "blocked"].includes(saved.state)),
|
|
939
|
-
"assignment_task_ended",
|
|
940
|
-
);
|
|
941
|
-
const h = {
|
|
942
|
-
id: saved?.id ?? randomUUID(),
|
|
943
|
-
kind: "return",
|
|
944
|
-
assignmentId: a.id,
|
|
945
|
-
text: input.report,
|
|
946
|
-
from: "executor",
|
|
947
|
-
to: "coordinator",
|
|
948
|
-
executionId: this.turn.id,
|
|
949
|
-
toolCallId: callId,
|
|
950
|
-
basisUserEntryId: this.turn.basisUserEntryId,
|
|
951
|
-
state: "pending",
|
|
952
|
-
reportRevision: (saved?.reportRevision ?? 0) + 1,
|
|
953
|
-
outcome: input.outcome,
|
|
954
|
-
limitations: input.limitations ?? [],
|
|
955
|
-
};
|
|
956
|
-
this.append({ type: "return-accepted", handoff: h }, op);
|
|
957
|
-
return this.returnReadiness(h.id);
|
|
958
|
-
}
|
|
959
|
-
returnReadiness(id) {
|
|
960
|
-
const h = this.stateData().handoffs.get(id);
|
|
961
|
-
const prepared = this.prepared("coordinator", this.messages, id);
|
|
962
|
-
return {
|
|
963
|
-
status: "accepted",
|
|
964
|
-
reportSaved: true,
|
|
965
|
-
handoff: id,
|
|
966
|
-
reportRevision: h.reportRevision,
|
|
967
|
-
assignmentRef: `assignment:${h.assignmentId}`,
|
|
968
|
-
reportRef: `report:${h.id}:${h.reportRevision}`,
|
|
969
|
-
producer: "executor",
|
|
970
|
-
outcome: h.outcome,
|
|
971
|
-
limitations: h.limitations,
|
|
972
|
-
ready: prepared.ready,
|
|
973
|
-
transition: prepared.ready ? "pending" : "blocked",
|
|
974
|
-
problems: prepared.problems,
|
|
975
|
-
warnings: prepared.warnings,
|
|
976
|
-
stage: "completed-input preparation",
|
|
977
|
-
finalExchangePending: true,
|
|
978
|
-
provisional:
|
|
979
|
-
"The finalized handoff exchange, target configuration and budget are revalidated at turn_end; this is not delivery evidence.",
|
|
980
|
-
report: h.text,
|
|
981
|
-
evidence: this.evidenceFacts(this.stateData()),
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
|
-
project(input, op) {
|
|
985
|
-
check(this.projectionEnabled, "projection_disabled");
|
|
986
|
-
const state = this.stateData(),
|
|
987
|
-
a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
988
|
-
check(a, "assignment_missing");
|
|
989
|
-
const sources = this.sources(state);
|
|
990
|
-
sources.associate(this.messages);
|
|
991
|
-
const selection = state.selections.get(a.id) ?? emptySelection();
|
|
992
|
-
let next = selection;
|
|
993
|
-
if (input.operation !== "inspect") {
|
|
994
|
-
check(["add", "remove"].includes(input.operation), "invalid_projection_operation");
|
|
995
|
-
next = changeSelection(selection, input, sources, state);
|
|
996
|
-
if (next !== selection) this.append({ type: "selection-changed", assignmentId: a.id, selection: next }, op);
|
|
997
|
-
}
|
|
998
|
-
const prepared = this.prepared("coordinator", this.messages, a.returnHandoffId);
|
|
999
|
-
const scope = input.scope ?? "assignment";
|
|
1000
|
-
let page;
|
|
1001
|
-
if (input.operation === "inspect") {
|
|
1002
|
-
const model = this.model("coordinator");
|
|
1003
|
-
const checksFor = (s) => {
|
|
1004
|
-
const eligibility = sources.selectionProblem(s.ref, state);
|
|
1005
|
-
const limitations = [
|
|
1006
|
-
...(eligibility ? [eligibility] : []),
|
|
1007
|
-
...representationProblems(s, model),
|
|
1008
|
-
...sources.exchange(s).problems,
|
|
1009
|
-
];
|
|
1010
|
-
return { eligible: !eligibility, targetReady: !limitations.length, limitations };
|
|
1011
|
-
};
|
|
1012
|
-
const rows = () =>
|
|
1013
|
-
[...sources.byRef.values()]
|
|
1014
|
-
.filter(
|
|
1015
|
-
(s) =>
|
|
1016
|
-
s.producer === "executor" &&
|
|
1017
|
-
(isTaskEvidence(s) || (scope === "selected" && next.selected.includes(s.ref))) &&
|
|
1018
|
-
(scope === "selected"
|
|
1019
|
-
? next.selected.includes(s.ref)
|
|
1020
|
-
: scope === "assignment"
|
|
1021
|
-
? s.assignmentId === a.id
|
|
1022
|
-
: scope === "active"
|
|
1023
|
-
? s.active
|
|
1024
|
-
: true) &&
|
|
1025
|
-
(s.original ||
|
|
1026
|
-
s.message.role === "toolResult" ||
|
|
1027
|
-
s.message.content?.some((b) => b.type === "text" && b.text?.trim())),
|
|
1028
|
-
)
|
|
1029
|
-
.map((s) => {
|
|
1030
|
-
return {
|
|
1031
|
-
ref: s.ref,
|
|
1032
|
-
kind: s.original ? "assistant-text" : s.message.role,
|
|
1033
|
-
producer: s.producer,
|
|
1034
|
-
assignment: s.assignmentId,
|
|
1035
|
-
toolName: s.message.toolName,
|
|
1036
|
-
active: s.active,
|
|
1037
|
-
selected: next.selected.includes(s.ref),
|
|
1038
|
-
retainedSelection: next.selected.includes(s.ref) && !isTaskEvidence(s),
|
|
1039
|
-
...checksFor(s),
|
|
1040
|
-
};
|
|
1041
|
-
})
|
|
1042
|
-
// Discovery offers usable candidates. Saved selections must remain
|
|
1043
|
-
// inspectable even when a later source or target check fails.
|
|
1044
|
-
.filter((row) => scope === "selected" || row.targetReady);
|
|
1045
|
-
page = this.page(
|
|
1046
|
-
`evidence:${scope}`,
|
|
1047
|
-
rows,
|
|
1048
|
-
input.cursor,
|
|
1049
|
-
30,
|
|
1050
|
-
scope === "assignment" || scope === "selected" ? a.id : undefined,
|
|
1051
|
-
scope === "active",
|
|
1052
|
-
(rows) => ({
|
|
1053
|
-
scopeCounts: {
|
|
1054
|
-
candidates: rows.length,
|
|
1055
|
-
eligible: rows.filter((r) => r.eligible).length,
|
|
1056
|
-
targetReady: rows.filter((r) => r.targetReady).length,
|
|
1057
|
-
},
|
|
1058
|
-
otherAssignments: [...sources.byRef.values()].filter(
|
|
1059
|
-
(s) =>
|
|
1060
|
-
s.producer === "executor" && s.assignmentId !== a.id && isTaskEvidence(s) && checksFor(s).targetReady,
|
|
1061
|
-
).length,
|
|
1062
|
-
}),
|
|
1063
|
-
);
|
|
1064
|
-
}
|
|
1065
|
-
return {
|
|
1066
|
-
status: input.operation === "inspect" || next === selection ? "unchanged" : "saved",
|
|
1067
|
-
...(page
|
|
1068
|
-
? {
|
|
1069
|
-
scope,
|
|
1070
|
-
count: page.count,
|
|
1071
|
-
returned: page.items.length,
|
|
1072
|
-
candidates: page.items,
|
|
1073
|
-
nextCursor: page.nextCursor,
|
|
1074
|
-
...page.summary,
|
|
1075
|
-
pageCounts: {
|
|
1076
|
-
candidates: page.items.length,
|
|
1077
|
-
eligible: page.items.filter((r) => r.eligible).length,
|
|
1078
|
-
targetReady: page.items.filter((r) => r.targetReady).length,
|
|
1079
|
-
},
|
|
1080
|
-
countsBasis:
|
|
1081
|
-
"Inspection snapshot; page counts describe returned candidates, scope counts describe all candidates in this scope.",
|
|
1082
|
-
historyHint: page.summary.otherAssignments
|
|
1083
|
-
? "Previously exposed task evidence exists in other assignments; inspect scope history when needed."
|
|
1084
|
-
: undefined,
|
|
1085
|
-
}
|
|
1086
|
-
: {}),
|
|
1087
|
-
revision: next.revision,
|
|
1088
|
-
selected: next.selected,
|
|
1089
|
-
selectedCount: next.selected.length,
|
|
1090
|
-
unresolved: next.unresolved,
|
|
1091
|
-
ready: !next.unresolved.length && prepared.ready,
|
|
1092
|
-
problems: prepared.problems,
|
|
1093
|
-
warnings: prepared.warnings,
|
|
1094
|
-
evidence: this.evidenceFacts(this.stateData()),
|
|
1095
|
-
items: (input.refs ? [...new Set(input.refs)] : []).map((ref) => ({
|
|
1096
|
-
ref,
|
|
1097
|
-
status: next.unresolved.some((p) => p.ref === ref)
|
|
1098
|
-
? "rejected"
|
|
1099
|
-
: input.operation === "remove"
|
|
1100
|
-
? selection.selected.includes(ref)
|
|
1101
|
-
? "removed"
|
|
1102
|
-
: selection.unresolved.some((p) => p.ref === ref)
|
|
1103
|
-
? "withdrawn"
|
|
1104
|
-
: "unchanged"
|
|
1105
|
-
: selection.selected.includes(ref)
|
|
1106
|
-
? "already_selected"
|
|
1107
|
-
: "added",
|
|
1108
|
-
})),
|
|
1109
|
-
estimate: { tokens: prepared.estimatedTokens, method: prepared.estimateMethod },
|
|
1110
|
-
};
|
|
1111
|
-
}
|
|
1112
|
-
unit(input, op) {
|
|
1113
|
-
const state = this.stateData();
|
|
1114
|
-
const prior = [...state.events.values()].find((e) => e.operationId === op);
|
|
1115
|
-
if (prior) {
|
|
1116
|
-
check(
|
|
1117
|
-
(input.operation === "assess" && prior.data.type === "assessment-resumed") ||
|
|
1118
|
-
(input.operation === "close" &&
|
|
1119
|
-
prior.data.type === "unit-closed" &&
|
|
1120
|
-
prior.data.outcome === input.outcome &&
|
|
1121
|
-
prior.data.assessment === input.assessment),
|
|
1122
|
-
"operation_conflict",
|
|
1123
|
-
);
|
|
1124
|
-
return { status: "unchanged", operation: input.operation };
|
|
1125
|
-
}
|
|
1126
|
-
if (input.operation === "assess") {
|
|
1127
|
-
check(state.assessment, "assessment_missing");
|
|
1128
|
-
if (state.assessment.view === "active") return { status: "unchanged", ready: true };
|
|
1129
|
-
const prepared = this.prepared("coordinator", this.messages, state.assessment.handoffId, true);
|
|
1130
|
-
if (!prepared.ready) return { status: "suspended", ready: false, problems: prepared.problems };
|
|
1131
|
-
check(prepared.reservation, "reservation_missing");
|
|
1132
|
-
this.append(
|
|
1133
|
-
{
|
|
1134
|
-
type: "assessment-resumed",
|
|
1135
|
-
handoffId: state.assessment.handoffId,
|
|
1136
|
-
basisUserEntryId: this.turn.basisUserEntryId,
|
|
1137
|
-
reservation: prepared.reservation,
|
|
1138
|
-
},
|
|
1139
|
-
op,
|
|
1140
|
-
);
|
|
1141
|
-
this.projectionError = undefined;
|
|
1142
|
-
return {
|
|
1143
|
-
status: "resumed",
|
|
1144
|
-
ready: true,
|
|
1145
|
-
stage: "prepared assessment; next request revalidated",
|
|
1146
|
-
evidence: this.evidenceFacts(this.stateData()),
|
|
1147
|
-
};
|
|
1148
|
-
}
|
|
1149
|
-
check(input.operation === "close" && state.unitId, "unit_missing");
|
|
1150
|
-
const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
1151
|
-
check(!this.applying, "not_quiescent");
|
|
1152
|
-
this.append(
|
|
1153
|
-
{
|
|
1154
|
-
type: "unit-closed",
|
|
1155
|
-
unitId: state.unitId,
|
|
1156
|
-
outcome: input.outcome,
|
|
1157
|
-
assessment: input.assessment,
|
|
1158
|
-
...(a?.state === "outstanding" && input.outcome !== "accepted" ? { supersededAssignmentId: a.id } : {}),
|
|
1159
|
-
},
|
|
1160
|
-
op,
|
|
1161
|
-
);
|
|
1162
|
-
return { status: "closed", unit: state.unitId, outcome: input.outcome, assessment: input.assessment };
|
|
1163
|
-
}
|
|
1164
|
-
page(scope, rows, cursor, size = 30, assignment, active = false, summarize) {
|
|
1165
|
-
const branch = this.ctx.sessionManager.getBranch();
|
|
1166
|
-
const compaction = branch.filter((e) => e.type === "compaction").at(-1)?.id;
|
|
1167
|
-
let key,
|
|
1168
|
-
offset = 0;
|
|
1169
|
-
if (cursor) {
|
|
1170
|
-
const match = /^([a-f0-9-]+):([0-9]+)$/.exec(cursor);
|
|
1171
|
-
check(match, "invalid_cursor", "Use the returned cursor unchanged.");
|
|
1172
|
-
key = match[1];
|
|
1173
|
-
offset = Number(match[2]);
|
|
1174
|
-
const page = this.pages.get(key);
|
|
1175
|
-
check(
|
|
1176
|
-
page &&
|
|
1177
|
-
page.scope === scope &&
|
|
1178
|
-
page.assignment === assignment &&
|
|
1179
|
-
(!page.basis || branch.some((e) => e.id === page.basis)) &&
|
|
1180
|
-
(!active || page.compaction === compaction),
|
|
1181
|
-
"cursor_expired",
|
|
1182
|
-
"History or scope changed. Inspect again without a cursor.",
|
|
1183
|
-
);
|
|
1184
|
-
check(
|
|
1185
|
-
Number.isSafeInteger(offset) && offset >= 0 && offset < page.rows.length && offset % page.size === 0,
|
|
1186
|
-
"invalid_cursor",
|
|
1187
|
-
);
|
|
1188
|
-
} else {
|
|
1189
|
-
key = randomUUID();
|
|
1190
|
-
if (this.pages.size >= 8) this.pages.delete(this.pages.keys().next().value);
|
|
1191
|
-
const items = typeof rows === "function" ? rows() : rows;
|
|
1192
|
-
this.pages.set(key, {
|
|
1193
|
-
scope,
|
|
1194
|
-
basis: branch.at(-1)?.id ?? null,
|
|
1195
|
-
assignment,
|
|
1196
|
-
compaction,
|
|
1197
|
-
rows: items,
|
|
1198
|
-
size,
|
|
1199
|
-
summary: summarize?.(items),
|
|
1200
|
-
});
|
|
1201
|
-
}
|
|
1202
|
-
const page = this.pages.get(key);
|
|
1203
|
-
return {
|
|
1204
|
-
scope,
|
|
1205
|
-
count: page.rows.length,
|
|
1206
|
-
offset,
|
|
1207
|
-
summary: page.summary,
|
|
1208
|
-
items: page.rows.slice(offset, offset + page.size),
|
|
1209
|
-
nextCursor: offset + page.size < page.rows.length ? `${key}:${offset + page.size}` : undefined,
|
|
1210
|
-
};
|
|
1211
|
-
}
|
|
1212
|
-
inspectUnit(input) {
|
|
1213
|
-
const state = this.stateData(),
|
|
1214
|
-
view = input.view ?? "current";
|
|
1215
|
-
check(view === "detail" || !input.ref, "invalid_inspection", "A work ref belongs to view detail.");
|
|
1216
|
-
check(
|
|
1217
|
-
view === "history" || (!input.cursor && !input.limit),
|
|
1218
|
-
"invalid_inspection",
|
|
1219
|
-
"Pagination belongs to view history.",
|
|
1220
|
-
);
|
|
1221
|
-
if (view === "current")
|
|
1222
|
-
return {
|
|
1223
|
-
...this.status(),
|
|
1224
|
-
status: "inspected",
|
|
1225
|
-
view,
|
|
1226
|
-
currentRef: state.assignmentId ? `assignment:${state.assignmentId}` : undefined,
|
|
1227
|
-
};
|
|
1228
|
-
if (view === "history") {
|
|
1229
|
-
const numbers = new Map([...state.units.keys()].map((id, i) => [id, i + 1]));
|
|
1230
|
-
const rows = () =>
|
|
1231
|
-
[...state.assignments.values()].reverse().map((a) => {
|
|
1232
|
-
const u = state.units.get(a.unitId),
|
|
1233
|
-
h = a.returnHandoffId ? state.handoffs.get(a.returnHandoffId) : undefined;
|
|
1234
|
-
return {
|
|
1235
|
-
ref: `assignment:${a.id}`,
|
|
1236
|
-
unitRef: `unit:${a.unitId}`,
|
|
1237
|
-
unitNumber: numbers.get(a.unitId),
|
|
1238
|
-
assignmentNumber: (u?.assignmentIds.indexOf(a.id) ?? 0) + 1,
|
|
1239
|
-
state: a.state,
|
|
1240
|
-
unitState: u?.state,
|
|
1241
|
-
disposition: u?.disposition,
|
|
1242
|
-
summary: a.contract.slice(0, 160),
|
|
1243
|
-
reportAvailable: !!h,
|
|
1244
|
-
outcome: h?.outcome,
|
|
1245
|
-
from: "coordinator",
|
|
1246
|
-
to: "executor",
|
|
1247
|
-
};
|
|
1248
|
-
});
|
|
1249
|
-
const page = this.page("work-history", rows, input.cursor, input.limit ?? 20);
|
|
1250
|
-
return {
|
|
1251
|
-
status: "inspected",
|
|
1252
|
-
view,
|
|
1253
|
-
history: page.items,
|
|
1254
|
-
count: page.count,
|
|
1255
|
-
returned: page.items.length,
|
|
1256
|
-
nextCursor: page.nextCursor,
|
|
1257
|
-
};
|
|
1258
|
-
}
|
|
1259
|
-
check(
|
|
1260
|
-
view === "detail" && typeof input.ref === "string",
|
|
1261
|
-
"work_ref_required",
|
|
1262
|
-
"Use a ref returned by history inspection.",
|
|
1263
|
-
);
|
|
1264
|
-
check(
|
|
1265
|
-
/^(?:(?:unit|assignment):[^:\s]+|report:[^:\s]+:[1-9][0-9]*)$/.test(input.ref),
|
|
1266
|
-
"invalid_work_ref",
|
|
1267
|
-
"Use assignmentRef or reportRef from the return receipt, or a work ref returned by inspection, unchanged. A bare handoff ID is not a work ref.",
|
|
1268
|
-
);
|
|
1269
|
-
if (input.ref.startsWith("unit:")) {
|
|
1270
|
-
const u = state.units.get(input.ref.slice(5));
|
|
1271
|
-
check(u, "work_unavailable", "Unit is not on current ancestry.");
|
|
1272
|
-
return {
|
|
1273
|
-
status: "inspected",
|
|
1274
|
-
view,
|
|
1275
|
-
ref: input.ref,
|
|
1276
|
-
unit: {
|
|
1277
|
-
id: u.id,
|
|
1278
|
-
state: u.state,
|
|
1279
|
-
objective: u.objective,
|
|
1280
|
-
disposition: u.disposition,
|
|
1281
|
-
assessment: u.assessment,
|
|
1282
|
-
},
|
|
1283
|
-
assignmentCount: u.assignmentIds.length,
|
|
1284
|
-
assignmentRefs: u.assignmentIds.slice(0, 30).map((id) => `assignment:${id}`),
|
|
1285
|
-
remaining: Math.max(0, u.assignmentIds.length - 30),
|
|
1286
|
-
historyHint: "Use paginated history inspection for all assignment refs.",
|
|
1287
|
-
historical: true,
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
let savedRevision;
|
|
1291
|
-
if (input.ref.startsWith("report:")) {
|
|
1292
|
-
const match = /^report:([^:]+):([0-9]+)$/.exec(input.ref);
|
|
1293
|
-
check(match, "work_unavailable", "Use a report ref returned by detail inspection.");
|
|
1294
|
-
for (const event of state.events.values())
|
|
1295
|
-
if (
|
|
1296
|
-
event.data.type === "return-accepted" &&
|
|
1297
|
-
event.data.handoff.id === match[1] &&
|
|
1298
|
-
event.data.handoff.reportRevision === Number(match[2])
|
|
1299
|
-
)
|
|
1300
|
-
savedRevision = event.data.handoff;
|
|
1301
|
-
check(savedRevision, "work_unavailable", "Report revision is not on current ancestry.");
|
|
1302
|
-
}
|
|
1303
|
-
const a = savedRevision
|
|
1304
|
-
? state.assignments.get(savedRevision.assignmentId)
|
|
1305
|
-
: input.ref.startsWith("assignment:")
|
|
1306
|
-
? state.assignments.get(input.ref.slice(11))
|
|
1307
|
-
: undefined;
|
|
1308
|
-
check(a, "work_unavailable", "Assignment is not on current ancestry.");
|
|
1309
|
-
const latest = a.returnHandoffId ? state.handoffs.get(a.returnHandoffId) : undefined;
|
|
1310
|
-
const h = savedRevision ?? latest;
|
|
1311
|
-
return {
|
|
1312
|
-
status: "inspected",
|
|
1313
|
-
view,
|
|
1314
|
-
ref: input.ref,
|
|
1315
|
-
historical: a.id !== state.assignmentId || a.state !== "outstanding",
|
|
1316
|
-
assignment: { id: a.id, unitId: a.unitId, state: a.state },
|
|
1317
|
-
contract: a.contract,
|
|
1318
|
-
report: h?.text,
|
|
1319
|
-
reportRevision: h?.reportRevision,
|
|
1320
|
-
latestReportRevision: latest?.reportRevision,
|
|
1321
|
-
reportRef: h ? `report:${h.id}:${h.reportRevision}` : undefined,
|
|
1322
|
-
previousReportRef: h && h.reportRevision > 1 ? `report:${h.id}:${h.reportRevision - 1}` : undefined,
|
|
1323
|
-
outcome: h?.outcome,
|
|
1324
|
-
limitations: h?.limitations,
|
|
1325
|
-
handoff: h?.id,
|
|
1326
|
-
currentSelection: state.selections.get(a.id) ?? emptySelection(),
|
|
1327
|
-
sourceBoundary:
|
|
1328
|
-
"Accepted report revision on current ancestry; assignment/selection show current recorded state. Historical content grants no current permission.",
|
|
1329
|
-
};
|
|
1330
|
-
}
|
|
1331
|
-
status(limit = 0) {
|
|
1332
|
-
const state = this.stateData();
|
|
1333
|
-
const unit = state.unitId ? state.units.get(state.unitId) : undefined;
|
|
1334
|
-
const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
1335
|
-
return {
|
|
1336
|
-
...this.state(),
|
|
1337
|
-
unit: unit ? { id: unit.id, state: unit.state, assignments: unit.assignmentIds.length } : null,
|
|
1338
|
-
assignment: a ? { id: a.id, state: a.state } : null,
|
|
1339
|
-
pendingHandoff: state.pendingId ?? null,
|
|
1340
|
-
assessment: state.assessment
|
|
1341
|
-
? { handoffId: state.assessment.handoffId, view: state.assessment.view, problems: state.assessment.problems }
|
|
1342
|
-
: null,
|
|
1343
|
-
...(limit
|
|
1344
|
-
? {
|
|
1345
|
-
history: [...state.events.values()]
|
|
1346
|
-
.slice(-Math.min(100, Math.max(1, limit)))
|
|
1347
|
-
.map((e) => ({ event: e.eventId, type: e.data.type, operation: e.operationId })),
|
|
1348
|
-
}
|
|
1349
|
-
: {}),
|
|
1350
|
-
};
|
|
1351
|
-
}
|
|
1352
|
-
async turnEnd(event, ctx) {
|
|
1353
|
-
this.ctx = ctx;
|
|
1354
|
-
if (!this.turn || this.turn.bound || !this.supported() || !this.store) return;
|
|
1355
|
-
if (!this.turn.opened) {
|
|
1356
|
-
this.turn = undefined;
|
|
1357
|
-
return;
|
|
1358
|
-
}
|
|
1359
|
-
const token = this.token,
|
|
1360
|
-
turn = this.turn;
|
|
1361
|
-
const subject = this.subject();
|
|
1362
|
-
try {
|
|
1363
|
-
const message = event.message ?? turn.message;
|
|
1364
|
-
const candidates = ctx.sessionManager
|
|
1365
|
-
.getBranch()
|
|
1366
|
-
.filter((e) => !turn.before.has(e.id) && e.type === "message" && canonical(e.message) === canonical(message));
|
|
1367
|
-
check(candidates.length === 1, "execution_binding_ambiguous");
|
|
1368
|
-
const assistant = candidates[0];
|
|
1369
|
-
const callIds = new Set((message?.content ?? []).filter((b) => b.type === "toolCall").map((b) => b.id));
|
|
1370
|
-
const results = ctx.sessionManager
|
|
1371
|
-
.getBranch()
|
|
1372
|
-
.filter((e) => !turn.before.has(e.id) && e.message?.role === "toolResult" && callIds.has(e.message.toolCallId));
|
|
1373
|
-
const outcome =
|
|
1374
|
-
message?.stopReason === "error" ? "failed" : message?.stopReason === "aborted" ? "aborted" : "completed";
|
|
1375
|
-
this.append(
|
|
1376
|
-
{
|
|
1377
|
-
type: "execution-bound",
|
|
1378
|
-
executionId: turn.id,
|
|
1379
|
-
assistantEntryId: assistant.id,
|
|
1380
|
-
resultEntryIds: results.map((e) => e.id),
|
|
1381
|
-
outcome,
|
|
1382
|
-
},
|
|
1383
|
-
JSON.stringify(["binding", turn.id]),
|
|
1384
|
-
);
|
|
1385
|
-
turn.bound = assistant.id;
|
|
1386
|
-
const state = this.stateData(),
|
|
1387
|
-
pending = state.pendingId ? state.handoffs.get(state.pendingId) : undefined;
|
|
1388
|
-
if (!pending || pending.state === "superseded") return;
|
|
1389
|
-
const attempt = state.attempts.get(pending.id);
|
|
1390
|
-
if (pending.executionId !== turn.id && attempt?.executionId !== turn.id) return;
|
|
1391
|
-
if (ctx.signal?.aborted || outcome === "aborted" || state.control !== "automatic") return;
|
|
1392
|
-
const inputs = [...this.messages, message, ...results.map((e) => e.message)].filter(Boolean);
|
|
1393
|
-
const latest = this.stateData();
|
|
1394
|
-
const retry = latest.attempts.get(pending.id);
|
|
1395
|
-
if (retry?.executionId === turn.id)
|
|
1396
|
-
check(
|
|
1397
|
-
retry.reportRevision === pending.reportRevision &&
|
|
1398
|
-
retry.selectionRevision === (latest.selections.get(pending.assignmentId)?.revision ?? 0),
|
|
1399
|
-
"stale_retry_revision",
|
|
1400
|
-
);
|
|
1401
|
-
await this.finishHandoff(pending, inputs, token);
|
|
1402
|
-
} catch (error) {
|
|
1403
|
-
if (this.current(subject)) {
|
|
1404
|
-
this.mark(error);
|
|
1405
|
-
ctx.abort?.();
|
|
1406
|
-
}
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
async finishHandoff(h, inputs, token) {
|
|
1410
|
-
const subject = this.subject();
|
|
1411
|
-
const state = this.stateData();
|
|
1412
|
-
check(state.control === "automatic" && !this.store?.blocked && token === this.token, "transition_ineligible");
|
|
1413
|
-
const execution = state.executions.get(h.executionId);
|
|
1414
|
-
check(
|
|
1415
|
-
execution?.assistantEntryId,
|
|
1416
|
-
"source_turn_incomplete",
|
|
1417
|
-
"Saved communication belongs to an incomplete historical turn. Reconcile its effects and replace or cancel the outstanding work; no tool result is fabricated.",
|
|
1418
|
-
);
|
|
1419
|
-
const source = new Sources(this.ctx.sessionManager.getBranch(), state);
|
|
1420
|
-
const carrier = source.byRef.get(`ctx:${execution.assistantEntryId}`);
|
|
1421
|
-
check(
|
|
1422
|
-
carrier && !source.exchange(carrier).problems.length,
|
|
1423
|
-
"source_exchange_incomplete",
|
|
1424
|
-
"The saved handoff has an incomplete native exchange; reconcile or explicitly dispose of it.",
|
|
1425
|
-
);
|
|
1426
|
-
if (h.kind === "return" && this.projectionEnabled) {
|
|
1427
|
-
const prepared = this.prepared("coordinator", inputs, h.id);
|
|
1428
|
-
if (!prepared.ready) {
|
|
1429
|
-
this.projectionError = prepared.problems.map((p) => p.code).join(", ");
|
|
1430
|
-
this.append({
|
|
1431
|
-
type: "handoff-state",
|
|
1432
|
-
handoffId: h.id,
|
|
1433
|
-
state: "blocked",
|
|
1434
|
-
reason: prepared.problems
|
|
1435
|
-
.map((p) => p.detail)
|
|
1436
|
-
.join("; ")
|
|
1437
|
-
.slice(0, 4096),
|
|
1438
|
-
});
|
|
1439
|
-
return;
|
|
1440
|
-
}
|
|
1441
|
-
check(prepared.reservation, "reservation_missing");
|
|
1442
|
-
this.append({ type: "handoff-prepared", handoffId: h.id, reservation: prepared.reservation });
|
|
1443
|
-
}
|
|
1444
|
-
try {
|
|
1445
|
-
const current = this.stateData();
|
|
1446
|
-
check(current.pendingId === h.id && current.control === "automatic" && token === this.token, "stale_handoff");
|
|
1447
|
-
await this.applyPair(this.profilePair(h.to));
|
|
1448
|
-
this.guard(subject);
|
|
1449
|
-
this.append({ type: "handoff-state", handoffId: h.id, state: "configured", observedPair: this.observed() });
|
|
1450
|
-
const completed = this.stateData();
|
|
1451
|
-
const reservation = completed.reservations.get(h.id);
|
|
1452
|
-
if (h.kind === "return" && completed.assessment?.view === "suspended" && reservation) {
|
|
1453
|
-
this.append({
|
|
1454
|
-
type: "assessment-resumed",
|
|
1455
|
-
handoffId: h.id,
|
|
1456
|
-
basisUserEntryId: this.lastDeliveredUser(this.sources(completed), inputs),
|
|
1457
|
-
reservation,
|
|
1458
|
-
});
|
|
1459
|
-
}
|
|
1460
|
-
this.projectionError = undefined;
|
|
1461
|
-
} catch (error) {
|
|
1462
|
-
if (this.current(subject) && !this.store?.blocked && !this.error && this.stateData().pendingId === h.id) {
|
|
1463
|
-
this.append({
|
|
1464
|
-
type: "handoff-state",
|
|
1465
|
-
handoffId: h.id,
|
|
1466
|
-
state: "blocked",
|
|
1467
|
-
reason: error instanceof Error ? error.message.slice(0, 4096) : "configuration_failed",
|
|
1468
|
-
});
|
|
1469
|
-
this.ctx.ui?.notify?.(
|
|
1470
|
-
`Couldn’t switch to ${h.to === "coordinator" ? "Coordinator" : "Executor"} — ${h.kind === "return" ? "report" : "assignment"} saved.`,
|
|
1471
|
-
"warning",
|
|
1472
|
-
);
|
|
1473
|
-
} else throw error;
|
|
1474
|
-
}
|
|
1475
|
-
}
|
|
1476
|
-
async resume(ctx) {
|
|
1477
|
-
this.ctx = ctx;
|
|
1478
|
-
check(ctx.isIdle?.(), "not_idle");
|
|
1479
|
-
check(this.store && this.capability?.effective, "routing_unavailable");
|
|
1480
|
-
this.revision++;
|
|
1481
|
-
const subject = this.subject();
|
|
1482
|
-
return this.enqueue(() => this.resumeCurrent(ctx, subject));
|
|
1483
|
-
}
|
|
1484
|
-
async resumeCurrent(ctx, subject) {
|
|
1485
|
-
this.guard(subject);
|
|
1486
|
-
check(this.store, "routing_unavailable");
|
|
1487
|
-
await this.store.reconcile();
|
|
1488
|
-
this.guard(subject);
|
|
1489
|
-
this.error = undefined;
|
|
1490
|
-
this.retireUnbound("Explicit resume retires an interrupted attempt without claiming its effects completed.");
|
|
1491
|
-
const state = this.stateData();
|
|
1492
|
-
check(state.control === "automatic", "manual_control");
|
|
1493
|
-
check(
|
|
1494
|
-
!ctx.hasPendingMessages?.(),
|
|
1495
|
-
"pending_input",
|
|
1496
|
-
"Queued input must be delivered and reconciled before resuming Executor.",
|
|
1497
|
-
);
|
|
1498
|
-
const pending = state.pendingId ? state.handoffs.get(state.pendingId) : undefined;
|
|
1499
|
-
if (pending) {
|
|
1500
|
-
const source = ctx.sessionManager.buildSessionContext?.().messages;
|
|
1501
|
-
check(Array.isArray(source) || this.messages.length, "resume_context_unavailable");
|
|
1502
|
-
await this.finishHandoff(pending, source ?? this.messages, this.token);
|
|
1503
|
-
this.guard(subject);
|
|
1504
|
-
if (this.stateData().pendingId) {
|
|
1505
|
-
check(
|
|
1506
|
-
pending.kind === "return" && this.projectionError,
|
|
1507
|
-
"handoff_still_blocked",
|
|
1508
|
-
"Saved transfer is still blocked; reconcile its configuration before retrying.",
|
|
1509
|
-
);
|
|
1510
|
-
this.append({
|
|
1511
|
-
type: "control",
|
|
1512
|
-
control: "automatic",
|
|
1513
|
-
profile: "executor",
|
|
1514
|
-
reason: "Explicit resume of saved-return evidence correction only; ordinary assignment work remains ended",
|
|
1515
|
-
});
|
|
1516
|
-
await this.applyPair(this.profilePair("executor"));
|
|
1517
|
-
}
|
|
1518
|
-
} else {
|
|
1519
|
-
const assignment = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
|
|
1520
|
-
const input = ctx.sessionManager.buildSessionContext?.().messages ?? this.messages;
|
|
1521
|
-
const user = this.lastDeliveredUser(new Sources(ctx.sessionManager.getBranch(), state), input);
|
|
1522
|
-
const coordinatorSawInput = [...state.executions.values()].some(
|
|
1523
|
-
(x) =>
|
|
1524
|
-
x.profile === "coordinator" && x.basisUserEntryId === user && x.assistantEntryId && x.outcome === "completed",
|
|
1525
|
-
);
|
|
1526
|
-
if (assignment?.state === "outstanding") {
|
|
1527
|
-
check(
|
|
1528
|
-
user === this.taskBasis(state, assignment.id) || coordinatorSawInput,
|
|
1529
|
-
"input_unreconciled",
|
|
1530
|
-
"New input needs Coordinator attention before the unchanged assignment can resume.",
|
|
1531
|
-
);
|
|
1532
|
-
this.append({ type: "assignment-resumed", assignmentId: assignment.id, basisUserEntryId: user });
|
|
1533
|
-
this.append({
|
|
1534
|
-
type: "control",
|
|
1535
|
-
control: "automatic",
|
|
1536
|
-
profile: "executor",
|
|
1537
|
-
reason: "Explicit user resume of the unchanged assignment; current restrictions remain applicable",
|
|
1538
|
-
});
|
|
1539
|
-
await this.applyPair(this.profilePair("executor"));
|
|
1540
|
-
} else await this.applyPair(this.profilePair("coordinator"));
|
|
1541
|
-
}
|
|
1542
|
-
this.guard(subject);
|
|
1543
|
-
this.pi.sendMessage(
|
|
1544
|
-
{
|
|
1545
|
-
customType: "freeflow-routing-v2-resume",
|
|
1546
|
-
content:
|
|
1547
|
-
"Explicit user resume of the saved routing responsibility. Recover the current contract and evidence before continuing.",
|
|
1548
|
-
display: true,
|
|
1549
|
-
},
|
|
1550
|
-
{ triggerTurn: true },
|
|
1551
|
-
);
|
|
1552
|
-
}
|
|
1553
|
-
async command(args, ctx) {
|
|
1554
|
-
const words = args.trim().split(/\s+/);
|
|
1555
|
-
if (!["profile", "resume"].includes(words[0])) return false;
|
|
1556
|
-
try {
|
|
1557
|
-
if (words[0] === "profile" && words[1] === "history") {
|
|
1558
|
-
check(words.length === 2 || (words.length === 3 && words[2] === "diagnostics"), "invalid_history_command");
|
|
1559
|
-
ctx.ui.notify(
|
|
1560
|
-
JSON.stringify(
|
|
1561
|
-
words[2] === "diagnostics" ? this.status(30) : this.inspectUnit({ view: "history", limit: 30 }),
|
|
1562
|
-
),
|
|
1563
|
-
"info",
|
|
1564
|
-
);
|
|
1565
|
-
return true;
|
|
1566
|
-
}
|
|
1567
|
-
check(ctx.isIdle?.(), "not_idle");
|
|
1568
|
-
this.ctx = ctx;
|
|
1569
|
-
if (words[0] === "resume" && words.length === 1) {
|
|
1570
|
-
await this.resume(ctx);
|
|
1571
|
-
return true;
|
|
1572
|
-
}
|
|
1573
|
-
check(
|
|
1574
|
-
words.length === 2 && [...PROFILES, "auto"].includes(words[1]),
|
|
1575
|
-
"invalid_profile_command",
|
|
1576
|
-
"Use /freeflow profile coordinator|executor|auto|history, or /freeflow resume.",
|
|
1577
|
-
);
|
|
1578
|
-
const result = words[1] === "auto" ? await this.setAutomaticControl() : await this.setManualProfile(words[1]);
|
|
1579
|
-
ctx.ui.notify(JSON.stringify(result), result.status === "blocked" ? "warning" : "info");
|
|
1580
|
-
} catch (error) {
|
|
1581
|
-
ctx.ui.notify(error instanceof Error ? error.message : String(error), "warning");
|
|
1582
|
-
}
|
|
1583
|
-
return true;
|
|
1584
|
-
}
|
|
1585
|
-
}
|