@hassangameryt/freeflow 0.5.0 → 0.6.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/README.md +148 -154
- package/capabilities/cognitive-routing/SKILL.md +229 -0
- package/capabilities/context-virtualization/SKILL.md +103 -0
- package/capabilities/conversation-history/SKILL.md +53 -0
- package/command-surface.json +6 -13
- package/hooks/freeflow-runtime-context.mjs +35 -91
- package/hooks/tests/check-runtime-context-hook.sh +56 -39
- package/package.json +24 -16
- package/pi-extension/dist/cognitive-routing/commands.js +96 -0
- package/pi-extension/dist/cognitive-routing/config.js +236 -0
- package/pi-extension/dist/cognitive-routing/controller.js +862 -0
- package/pi-extension/dist/cognitive-routing/history.js +439 -0
- package/pi-extension/dist/cognitive-routing/host.js +126 -0
- package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
- package/pi-extension/dist/cognitive-routing/tool.js +211 -0
- package/pi-extension/dist/cognitive-routing/types.js +6 -0
- package/pi-extension/dist/context-virtualization/commands.js +89 -0
- package/pi-extension/dist/context-virtualization/projector.js +42 -0
- package/pi-extension/dist/context-virtualization/runtime.js +356 -0
- package/pi-extension/dist/context-virtualization/state.js +57 -0
- package/pi-extension/dist/context-virtualization/types.js +10 -0
- package/pi-extension/dist/conversation-history/passages.js +66 -0
- package/pi-extension/dist/conversation-history/ranking.js +105 -0
- package/pi-extension/dist/conversation-history/runtime.js +226 -0
- package/pi-extension/dist/conversation-history/search.js +56 -0
- package/pi-extension/dist/conversation-history/types.js +1 -0
- package/pi-extension/dist/freeflow-context/resolver.js +120 -0
- package/pi-extension/dist/freeflow-context/runtime.js +80 -0
- package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
- package/pi-extension/dist/freeflow-context/tool.js +308 -0
- package/pi-extension/dist/freeflow-context/types.js +12 -0
- package/pi-extension/dist/freeflow-context/visibility.js +28 -0
- package/pi-extension/dist/index.js +516 -98
- package/pi-extension/dist/runtime/runtime-context.js +318 -271
- package/pi-extension/dist/runtime/runtime-identity.js +5 -0
- package/pi-extension/dist/settings/settings-tui.js +78 -0
- package/pi-extension/dist/settings/settings-ui.js +593 -563
- package/pi-extension/dist/ui/text-component.js +57 -0
- package/pi-extension/src/cognitive-routing/commands.ts +119 -0
- package/pi-extension/src/cognitive-routing/config.ts +307 -0
- package/pi-extension/src/cognitive-routing/controller.ts +1118 -0
- package/pi-extension/src/cognitive-routing/history.ts +638 -0
- package/pi-extension/src/cognitive-routing/host.ts +172 -0
- package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
- package/pi-extension/src/cognitive-routing/tool.ts +272 -0
- package/pi-extension/src/cognitive-routing/types.ts +89 -0
- package/pi-extension/src/context-virtualization/commands.ts +111 -0
- package/pi-extension/src/context-virtualization/projector.ts +62 -0
- package/pi-extension/src/context-virtualization/runtime.ts +406 -0
- package/pi-extension/src/context-virtualization/state.ts +79 -0
- package/pi-extension/src/context-virtualization/types.ts +92 -0
- package/pi-extension/src/conversation-history/passages.ts +81 -0
- package/pi-extension/src/conversation-history/ranking.ts +155 -0
- package/pi-extension/src/conversation-history/runtime.ts +250 -0
- package/pi-extension/src/conversation-history/search.ts +79 -0
- package/pi-extension/src/conversation-history/types.ts +31 -0
- package/pi-extension/src/freeflow-context/resolver.ts +139 -0
- package/pi-extension/src/freeflow-context/runtime.ts +100 -0
- package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
- package/pi-extension/src/freeflow-context/tool.ts +360 -0
- package/pi-extension/src/freeflow-context/types.ts +70 -0
- package/pi-extension/src/freeflow-context/visibility.ts +53 -0
- package/pi-extension/src/index.ts +553 -101
- package/pi-extension/src/runtime/runtime-context.ts +339 -281
- package/pi-extension/src/runtime/runtime-identity.ts +8 -0
- package/pi-extension/src/settings/settings-tui.ts +93 -0
- package/pi-extension/src/settings/settings-ui.ts +700 -613
- package/pi-extension/src/ui/text-component.ts +66 -0
- package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
- package/pi-extension/tests/cognitive-routing/controller.test.js +1099 -0
- package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1071 -0
- package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
- package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
- package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
- package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +236 -0
- package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
- package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
- package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
- package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
- package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
- package/pi-extension/tests/conversation-history/search.test.js +97 -0
- package/pi-extension/tests/integration/pi-extension.test.js +927 -2048
- package/pi-extension/tests/integration/prompt-architecture.test.js +305 -0
- package/runtime/prompts/cognitive-routing.md +9 -0
- package/runtime/prompts/context-virtualization.md +3 -0
- package/runtime/prompts/conversation-history.md +3 -0
- package/runtime/prompts/core.md +13 -0
- package/runtime/prompts/interaction-contract.md +7 -0
- package/runtime/prompts/skills.md +65 -0
- package/skills/action-selection/SKILL.md +91 -0
- package/skills/bypass/SKILL.md +3 -2
- package/skills/commit-work/SKILL.md +1 -1
- package/skills/commit-work/references/staging-decisions.md +1 -1
- package/skills/decision-gate/SKILL.md +1 -1
- package/skills/design-for-depth/SKILL.md +14 -33
- package/skills/design-for-depth/references/design-pressure-signals.md +1 -1
- package/skills/design-for-depth/references/interface-design-loop.md +1 -1
- package/skills/design-for-depth/references/software-design-philosophy.md +1 -1
- package/skills/diagnose-failure/SKILL.md +20 -14
- package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +1 -3
- package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +1 -1
- package/skills/discuss/SKILL.md +34 -22
- package/skills/discuss/references/discussion-continuity.md +71 -0
- package/skills/evaluate-skill/SKILL.md +5 -5
- package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +42 -2
- package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
- package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
- package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
- package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
- package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
- package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
- package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
- package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
- package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
- package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
- package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
- package/skills/execute-work/SKILL.md +18 -15
- package/skills/execute-work/references/code-practices.md +1 -1
- package/skills/execute-work/references/execute-work-edges.md +42 -0
- package/skills/finish-branch/SKILL.md +2 -2
- package/skills/finish-branch/references/integration-options.md +1 -1
- package/skills/handoff/SKILL.md +3 -3
- package/skills/launch-work/SKILL.md +1 -1
- package/skills/launch-work/references/launch-readiness.md +2 -2
- package/skills/migration-work/SKILL.md +2 -2
- package/skills/migration-work/references/migration-lifecycle.md +1 -1
- package/skills/mode-contract/SKILL.md +4 -4
- package/skills/release-work/SKILL.md +1 -1
- package/skills/release-work/references/release-evidence.md +1 -1
- package/skills/review-artifact/SKILL.md +28 -26
- package/skills/review-work/SKILL.md +28 -26
- package/skills/review-work/references/{reviewer-prompt.md → independent-work-reviewer-contract.md} +1 -1
- package/skills/review-work/references/security-risk-lens.md +1 -1
- package/skills/setup-freeflow/SKILL.md +3 -1
- package/skills/setup-freeflow/references/activation-contract.md +2 -2
- package/skills/setup-freeflow/references/host-setup.md +2 -2
- package/skills/simplify-code/SKILL.md +1 -1
- package/skills/simplify-code/references/simplification-patterns.md +1 -1
- package/skills/tdd/SKILL.md +18 -38
- package/skills/tdd/references/test-design.md +2 -2
- package/skills/track-work/SKILL.md +362 -58
- package/skills/track-work/scripts/lib/codec.mjs +570 -0
- package/skills/track-work/scripts/lib/commands.mjs +568 -0
- package/skills/track-work/scripts/lib/contract.mjs +303 -0
- package/skills/track-work/scripts/lib/model.mjs +506 -0
- package/skills/track-work/scripts/lib/operations.mjs +965 -0
- package/skills/track-work/scripts/lib/record-store.mjs +264 -0
- package/skills/track-work/scripts/lib/result.mjs +37 -0
- package/skills/track-work/scripts/lib/rewrites.mjs +740 -0
- package/skills/track-work/scripts/lib/schema.mjs +277 -0
- package/skills/track-work/scripts/lib/source-inventory.mjs +162 -0
- package/skills/track-work/scripts/lib/views.mjs +443 -0
- package/skills/track-work/scripts/lib/workspace.mjs +134 -0
- package/skills/track-work/scripts/working-record.mjs +122 -0
- package/skills/verify-work/SKILL.md +14 -2
- package/skills/verify-work/references/browser-runtime-evidence.md +1 -1
- package/skills/verify-work/references/integration-evidence.md +1 -1
- package/skills/verify-work/references/performance-evidence.md +1 -1
- package/skills/workflow/SKILL.md +105 -53
- package/skills/workflow/references/domain-skill-composition.md +22 -42
- package/skills/write-plan/SKILL.md +1 -1
- package/skills/write-skill/SKILL.md +3 -2
- package/skills/write-skill/references/progressive-disclosure.md +17 -3
- package/capabilities/output-router/SKILL.md +0 -206
- package/capabilities/output-router/references/safety-policy.md +0 -40
- package/capabilities/output-router/references/setup.md +0 -110
- package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
- package/pi-extension/dist/output-router/native-safety-net.js +0 -216
- package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
- package/pi-extension/dist/output-router/renderers.js +0 -1023
- package/pi-extension/dist/output-router/router-tools.js +0 -554
- package/pi-extension/dist/output-router/schemas.js +0 -383
- package/pi-extension/dist/output-router/status.js +0 -744
- package/pi-extension/dist/output-router/utils.js +0 -502
- package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
- package/pi-extension/src/output-router/native-safety-net.ts +0 -248
- package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
- package/pi-extension/src/output-router/renderers.ts +0 -1108
- package/pi-extension/src/output-router/router-tools.ts +0 -579
- package/pi-extension/src/output-router/schemas.ts +0 -387
- package/pi-extension/src/output-router/status.ts +0 -791
- package/pi-extension/src/output-router/utils.ts +0 -554
- package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
- package/pi-extension/tests/output-router/search.test.js +0 -722
- package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
- package/router/dist/benchmarks/benchmark-harness.js +0 -92
- package/router/dist/benchmarks/benchmarks.d.ts +0 -109
- package/router/dist/benchmarks/benchmarks.js +0 -979
- package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
- package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
- package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
- package/router/dist/benchmarks/command-benchmarks.js +0 -698
- package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
- package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
- package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
- package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
- package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
- package/router/dist/benchmarks/context-saving-baseline.js +0 -470
- package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
- package/router/dist/benchmarks/index-benchmarks.js +0 -862
- package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
- package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
- package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
- package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
- package/router/dist/config/config.d.ts +0 -103
- package/router/dist/config/config.js +0 -632
- package/router/dist/config/router-contract.d.ts +0 -10
- package/router/dist/config/router-contract.js +0 -54
- package/router/dist/config/schema.d.ts +0 -27
- package/router/dist/config/schema.js +0 -648
- package/router/dist/config/types.d.ts +0 -573
- package/router/dist/config/types.js +0 -41
- package/router/dist/evidence/bounded-evidence.d.ts +0 -40
- package/router/dist/evidence/bounded-evidence.js +0 -323
- package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
- package/router/dist/evidence/evidence-range-selector.js +0 -232
- package/router/dist/evidence/evidence-search.d.ts +0 -27
- package/router/dist/evidence/evidence-search.js +0 -490
- package/router/dist/evidence/evidence.d.ts +0 -38
- package/router/dist/evidence/evidence.js +0 -200
- package/router/dist/evidence/failure-contracts.d.ts +0 -37
- package/router/dist/evidence/failure-contracts.js +0 -166
- package/router/dist/evidence/line-ranges.d.ts +0 -24
- package/router/dist/evidence/line-ranges.js +0 -22
- package/router/dist/experiments/local-index.d.ts +0 -64
- package/router/dist/experiments/local-index.js +0 -581
- package/router/dist/index.d.ts +0 -30
- package/router/dist/index.js +0 -32
- package/router/dist/local/local-traversal.d.ts +0 -18
- package/router/dist/local/local-traversal.js +0 -334
- package/router/dist/processing/engine.d.ts +0 -132
- package/router/dist/processing/engine.js +0 -533
- package/router/dist/processing/reducers.d.ts +0 -280
- package/router/dist/processing/reducers.js +0 -1673
- package/router/dist/processing/renderers.d.ts +0 -31
- package/router/dist/processing/renderers.js +0 -195
- package/router/dist/processing/scripts.d.ts +0 -91
- package/router/dist/processing/scripts.js +0 -386
- package/router/dist/repo/repo-traversal.d.ts +0 -18
- package/router/dist/repo/repo-traversal.js +0 -245
- package/router/dist/routing/observed-reducers.d.ts +0 -41
- package/router/dist/routing/observed-reducers.js +0 -661
- package/router/dist/routing/observed-routing.d.ts +0 -26
- package/router/dist/routing/observed-routing.js +0 -378
- package/router/dist/routing/parsers.d.ts +0 -16
- package/router/dist/routing/parsers.js +0 -521
- package/router/dist/routing/run-filters.d.ts +0 -60
- package/router/dist/routing/run-filters.js +0 -238
- package/router/dist/routing/run-reducers.d.ts +0 -49
- package/router/dist/routing/run-reducers.js +0 -122
- package/router/dist/sandbox/adapter-roots.d.ts +0 -46
- package/router/dist/sandbox/adapter-roots.js +0 -66
- package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
- package/router/dist/sandbox/eryx-python-adapter.js +0 -868
- package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
- package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
- package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
- package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
- package/router/dist/sandbox/script-sandbox.d.ts +0 -134
- package/router/dist/sandbox/script-sandbox.js +0 -337
- package/router/dist/setup/script-transform-adapters.d.ts +0 -32
- package/router/dist/setup/script-transform-adapters.js +0 -278
- package/router/dist/tools/batch.d.ts +0 -33
- package/router/dist/tools/batch.js +0 -586
- package/router/dist/tools/run.d.ts +0 -62
- package/router/dist/tools/run.js +0 -1304
- package/router/dist/tools/search.d.ts +0 -66
- package/router/dist/tools/search.js +0 -1364
- package/router/dist/transform/engine.d.ts +0 -168
- package/router/dist/transform/engine.js +0 -2072
- package/router/dist/vault/vault-index.d.ts +0 -125
- package/router/dist/vault/vault-index.js +0 -416
- package/router/dist/vault/vault.d.ts +0 -138
- package/router/dist/vault/vault.js +0 -630
- package/runtime/interaction-contract.md +0 -16
- package/skills/discuss/references/checkpoints.md +0 -66
- package/skills/execute-work/references/execution-loop.md +0 -77
- package/skills/track-work/references/working-record-schema.md +0 -378
- package/skills/workflow/references/workflow-loop.md +0 -92
- /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
- /package/skills/review-artifact/references/{reviewer-prompt.md → independent-artifact-reviewer-contract.md} +0 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { ContextSourceIdentity } from "../freeflow-context/types.js";
|
|
2
|
+
|
|
3
|
+
export { CONTEXT_REF_PREFIX, contextRefForEntry, entryIdFromContextRef } from "../freeflow-context/types.js";
|
|
4
|
+
export type {
|
|
5
|
+
ContextRequestSnapshot,
|
|
6
|
+
ContextSourceKind,
|
|
7
|
+
ContextSourceIdentity,
|
|
8
|
+
ProjectedContextSource,
|
|
9
|
+
ResolvedContextEntry,
|
|
10
|
+
ResolvedContextSource,
|
|
11
|
+
SourceProjectionOutcome,
|
|
12
|
+
} from "../freeflow-context/types.js";
|
|
13
|
+
|
|
14
|
+
export const CONTEXT_PROJECTION_ENTRY = "freeflow-context-projection";
|
|
15
|
+
export const CONTEXT_PROJECTION_VERSION = 1 as const;
|
|
16
|
+
|
|
17
|
+
export type ContextProjectionMode = "full" | "archived";
|
|
18
|
+
export type ContextProjectionActor = "model" | "user";
|
|
19
|
+
|
|
20
|
+
export type ContextProjection = { mode: "full" } | { mode: "archived"; retained?: string };
|
|
21
|
+
|
|
22
|
+
export type ContextProjectionState = ContextProjection & {
|
|
23
|
+
source: ContextSourceIdentity;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type ContextProjectionChange = {
|
|
27
|
+
source: ContextSourceIdentity;
|
|
28
|
+
projection: ContextProjection;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type ContextProjectionJournal = {
|
|
32
|
+
version: typeof CONTEXT_PROJECTION_VERSION;
|
|
33
|
+
actor: ContextProjectionActor;
|
|
34
|
+
changes?: ContextProjectionChange[];
|
|
35
|
+
reset?: "all";
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type ContextProjectionResult = {
|
|
39
|
+
messages: any[];
|
|
40
|
+
changed: boolean;
|
|
41
|
+
available: boolean;
|
|
42
|
+
generation?: number;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type ContextAvailability = "active" | "history-only" | "unresolved";
|
|
46
|
+
|
|
47
|
+
export type ContextListItem = {
|
|
48
|
+
ref: string;
|
|
49
|
+
entryId: string;
|
|
50
|
+
toolCallId?: string;
|
|
51
|
+
toolName?: string;
|
|
52
|
+
mode: ContextProjectionMode;
|
|
53
|
+
retained?: string;
|
|
54
|
+
originalCharacters: number;
|
|
55
|
+
projectedCharacters: number;
|
|
56
|
+
availability: ContextAvailability;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type ContextStatus = {
|
|
60
|
+
available: boolean;
|
|
61
|
+
unavailableReason?: string;
|
|
62
|
+
sessionId: string;
|
|
63
|
+
branchLeafId?: string | null;
|
|
64
|
+
counts: {
|
|
65
|
+
full: number;
|
|
66
|
+
archived: number;
|
|
67
|
+
retained: number;
|
|
68
|
+
};
|
|
69
|
+
originalCharacters: number;
|
|
70
|
+
projectedCharacters: number;
|
|
71
|
+
historyOnly: number;
|
|
72
|
+
unresolved: number;
|
|
73
|
+
items: ContextListItem[];
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export type ContextOperationResult = {
|
|
77
|
+
status: "ok" | "rejected" | "unavailable";
|
|
78
|
+
operation: "archive" | "restore" | "reset";
|
|
79
|
+
changed: string[];
|
|
80
|
+
message?: string;
|
|
81
|
+
retained?: Record<string, string>;
|
|
82
|
+
availability?: Record<string, ContextAvailability>;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
86
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function projectionCharacters(projection: ContextProjection): number {
|
|
90
|
+
if (projection.mode === "full") return 0;
|
|
91
|
+
return projection.retained?.length ?? 0;
|
|
92
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export const PASSAGE_TARGET_CHARACTERS = 2_000;
|
|
2
|
+
export const PASSAGE_OVERLAP_CHARACTERS = 200;
|
|
3
|
+
export const SNIPPET_MAX_CHARACTERS = 400;
|
|
4
|
+
|
|
5
|
+
export type TextPassage = {
|
|
6
|
+
text: string;
|
|
7
|
+
start: number;
|
|
8
|
+
end: number;
|
|
9
|
+
tokens: string[];
|
|
10
|
+
length: number;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function normalizeText(value: string): string {
|
|
14
|
+
return value.normalize("NFKC").toLocaleLowerCase().replace(/\s+/g, " ").trim();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function tokenize(value: string): string[] {
|
|
18
|
+
return normalizeText(value).match(/[\p{L}\p{N}_]+(?:[./:@#$%+-][\p{L}\p{N}_]+)*/gu) ?? [];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function unique(values: readonly string[]): string[] {
|
|
22
|
+
return [...new Set(values)];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function throwIfAborted(signal?: AbortSignal): void {
|
|
26
|
+
if (!signal?.aborted) return;
|
|
27
|
+
const error = new Error("conversation_history_search_cancelled");
|
|
28
|
+
error.name = "AbortError";
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function passageEnd(text: string, start: number): number {
|
|
33
|
+
const target = Math.min(text.length, start + PASSAGE_TARGET_CHARACTERS);
|
|
34
|
+
if (target === text.length) return target;
|
|
35
|
+
const paragraphBreak = text.lastIndexOf("\n\n", target);
|
|
36
|
+
if (paragraphBreak > start + PASSAGE_TARGET_CHARACTERS / 2) return paragraphBreak + 2;
|
|
37
|
+
const lineBreak = text.lastIndexOf("\n", target);
|
|
38
|
+
if (lineBreak > start + PASSAGE_TARGET_CHARACTERS / 2) return lineBreak + 1;
|
|
39
|
+
return target;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function splitTextIntoPassages(text: string, signal?: AbortSignal): TextPassage[] {
|
|
43
|
+
throwIfAborted(signal);
|
|
44
|
+
if (text.length <= PASSAGE_TARGET_CHARACTERS) {
|
|
45
|
+
return [{ text, start: 0, end: text.length, tokens: tokenize(text), length: Math.max(1, tokenize(text).length) }];
|
|
46
|
+
}
|
|
47
|
+
const result: TextPassage[] = [];
|
|
48
|
+
let start = 0;
|
|
49
|
+
while (start < text.length) {
|
|
50
|
+
throwIfAborted(signal);
|
|
51
|
+
const end = passageEnd(text, start);
|
|
52
|
+
const passageText = text.slice(start, end);
|
|
53
|
+
const tokens = tokenize(passageText);
|
|
54
|
+
result.push({ text: passageText, start, end, tokens, length: Math.max(1, tokens.length) });
|
|
55
|
+
if (end >= text.length) break;
|
|
56
|
+
start = Math.max(start + 1, end - PASSAGE_OVERLAP_CHARACTERS);
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function snippet(text: string, phrase: string, terms: readonly string[]): string {
|
|
62
|
+
if (text.length <= SNIPPET_MAX_CHARACTERS) return text;
|
|
63
|
+
const lower = text.toLocaleLowerCase();
|
|
64
|
+
const phraseIndex = phrase ? lower.indexOf(phrase) : -1;
|
|
65
|
+
const termIndex =
|
|
66
|
+
phraseIndex >= 0
|
|
67
|
+
? phraseIndex
|
|
68
|
+
: terms.reduce((best, term) => {
|
|
69
|
+
const index = lower.indexOf(term);
|
|
70
|
+
return index >= 0 && (best < 0 || index < best) ? index : best;
|
|
71
|
+
}, -1);
|
|
72
|
+
const center = termIndex >= 0 ? termIndex : 0;
|
|
73
|
+
let start = Math.max(0, center - Math.floor(SNIPPET_MAX_CHARACTERS / 3));
|
|
74
|
+
const end = Math.min(text.length, start + SNIPPET_MAX_CHARACTERS);
|
|
75
|
+
if (end - start < SNIPPET_MAX_CHARACTERS) start = Math.max(0, end - SNIPPET_MAX_CHARACTERS);
|
|
76
|
+
const prefix = start > 0 ? "…" : "";
|
|
77
|
+
const suffix = end < text.length ? "…" : "";
|
|
78
|
+
const available = SNIPPET_MAX_CHARACTERS - prefix.length - suffix.length;
|
|
79
|
+
const body = text.slice(start, start + available);
|
|
80
|
+
return `${prefix}${body}${suffix}`;
|
|
81
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { ConversationSearchEntry } from "./types.js";
|
|
2
|
+
import {
|
|
3
|
+
normalizeText,
|
|
4
|
+
splitTextIntoPassages,
|
|
5
|
+
throwIfAborted,
|
|
6
|
+
tokenize,
|
|
7
|
+
unique,
|
|
8
|
+
type TextPassage,
|
|
9
|
+
} from "./passages.js";
|
|
10
|
+
|
|
11
|
+
export const BM25_K1 = 1.2;
|
|
12
|
+
export const BM25_B = 0.75;
|
|
13
|
+
|
|
14
|
+
export type RankedPassage = {
|
|
15
|
+
entry: ConversationSearchEntry;
|
|
16
|
+
passage: TextPassage;
|
|
17
|
+
exactPhrase: boolean;
|
|
18
|
+
matchedTerms: string[];
|
|
19
|
+
score: number;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type RankedTextPassage = Omit<RankedPassage, "entry">;
|
|
23
|
+
|
|
24
|
+
type PassageInput = {
|
|
25
|
+
entry?: ConversationSearchEntry;
|
|
26
|
+
passage: TextPassage;
|
|
27
|
+
exactPhrase: boolean;
|
|
28
|
+
matchedTerms: string[];
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function bm25Score(
|
|
32
|
+
tokens: readonly string[],
|
|
33
|
+
terms: readonly string[],
|
|
34
|
+
documentFrequency: ReadonlyMap<string, number>,
|
|
35
|
+
documentCount: number,
|
|
36
|
+
averageLength: number,
|
|
37
|
+
): number {
|
|
38
|
+
const counts = new Map<string, number>();
|
|
39
|
+
for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1);
|
|
40
|
+
const length = Math.max(1, tokens.length);
|
|
41
|
+
let score = 0;
|
|
42
|
+
for (const term of terms) {
|
|
43
|
+
const termFrequency = counts.get(term) ?? 0;
|
|
44
|
+
if (termFrequency === 0) continue;
|
|
45
|
+
const df = documentFrequency.get(term) ?? 0;
|
|
46
|
+
const inverseDocumentFrequency = Math.log(1 + (documentCount - df + 0.5) / (df + 0.5));
|
|
47
|
+
const normalization = BM25_K1 * (1 - BM25_B + BM25_B * (length / Math.max(1, averageLength)));
|
|
48
|
+
score += inverseDocumentFrequency * ((termFrequency * (BM25_K1 + 1)) / (termFrequency + normalization));
|
|
49
|
+
}
|
|
50
|
+
return score;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function comparePassages(left: RankedPassage, right: RankedPassage): number {
|
|
54
|
+
if (left.exactPhrase !== right.exactPhrase) return left.exactPhrase ? -1 : 1;
|
|
55
|
+
if (left.score !== right.score) return right.score - left.score;
|
|
56
|
+
if (left.matchedTerms.length !== right.matchedTerms.length) {
|
|
57
|
+
return right.matchedTerms.length - left.matchedTerms.length;
|
|
58
|
+
}
|
|
59
|
+
if (left.entry.position !== right.entry.position) return right.entry.position - left.entry.position;
|
|
60
|
+
return left.passage.start - right.passage.start;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function compareTextPassages(left: RankedTextPassage, right: RankedTextPassage): number {
|
|
64
|
+
if (left.exactPhrase !== right.exactPhrase) return left.exactPhrase ? -1 : 1;
|
|
65
|
+
if (left.score !== right.score) return right.score - left.score;
|
|
66
|
+
if (left.matchedTerms.length !== right.matchedTerms.length) {
|
|
67
|
+
return right.matchedTerms.length - left.matchedTerms.length;
|
|
68
|
+
}
|
|
69
|
+
return left.passage.start - right.passage.start;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function rankInputs<T extends PassageInput>(
|
|
73
|
+
inputs: T[],
|
|
74
|
+
terms: string[],
|
|
75
|
+
signal?: AbortSignal,
|
|
76
|
+
): Array<T & { score: number }> {
|
|
77
|
+
const documentFrequency = new Map<string, number>();
|
|
78
|
+
for (const input of inputs) {
|
|
79
|
+
throwIfAborted(signal);
|
|
80
|
+
for (const term of unique(input.passage.tokens)) {
|
|
81
|
+
documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const averageLength =
|
|
85
|
+
inputs.length === 0 ? 1 : inputs.reduce((total, input) => total + input.passage.length, 0) / inputs.length;
|
|
86
|
+
const matching: T[] = [];
|
|
87
|
+
for (const input of inputs) {
|
|
88
|
+
throwIfAborted(signal);
|
|
89
|
+
if (input.matchedTerms.length > 0 || input.exactPhrase) matching.push(input);
|
|
90
|
+
}
|
|
91
|
+
return matching
|
|
92
|
+
.map((input) => ({
|
|
93
|
+
...input,
|
|
94
|
+
score: bm25Score(input.passage.tokens, terms, documentFrequency, inputs.length, averageLength),
|
|
95
|
+
}))
|
|
96
|
+
.sort((left, right) => {
|
|
97
|
+
if (left.entry && right.entry) {
|
|
98
|
+
return comparePassages(
|
|
99
|
+
{ ...left, entry: left.entry } as RankedPassage,
|
|
100
|
+
{ ...right, entry: right.entry } as RankedPassage,
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return compareTextPassages(left as RankedTextPassage & T, right as RankedTextPassage & T);
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function rankMatchingPassages(
|
|
108
|
+
entries: readonly ConversationSearchEntry[],
|
|
109
|
+
query: string,
|
|
110
|
+
signal?: AbortSignal,
|
|
111
|
+
): RankedPassage[] {
|
|
112
|
+
throwIfAborted(signal);
|
|
113
|
+
const normalizedQuery = normalizeText(query);
|
|
114
|
+
const terms = unique(tokenize(query));
|
|
115
|
+
if (!normalizedQuery || terms.length === 0) return [];
|
|
116
|
+
const inputs: PassageInput[] = [];
|
|
117
|
+
for (const entry of entries) {
|
|
118
|
+
throwIfAborted(signal);
|
|
119
|
+
for (const passage of splitTextIntoPassages(entry.text, signal)) {
|
|
120
|
+
const normalizedPassage = normalizeText(passage.text);
|
|
121
|
+
inputs.push({
|
|
122
|
+
entry,
|
|
123
|
+
passage,
|
|
124
|
+
exactPhrase: normalizedPassage.includes(normalizedQuery),
|
|
125
|
+
matchedTerms: terms.filter((term) => passage.tokens.includes(term)),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return rankInputs(inputs, terms, signal) as RankedPassage[];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function strongestTextPassage(text: string, query: string): RankedTextPassage | undefined {
|
|
133
|
+
const normalizedQuery = normalizeText(query);
|
|
134
|
+
const terms = unique(tokenize(query));
|
|
135
|
+
if (!normalizedQuery || terms.length === 0) return undefined;
|
|
136
|
+
const inputs: PassageInput[] = splitTextIntoPassages(text).map((passage) => ({
|
|
137
|
+
passage,
|
|
138
|
+
exactPhrase: normalizeText(passage.text).includes(normalizedQuery),
|
|
139
|
+
matchedTerms: terms.filter((term) => passage.tokens.includes(term)),
|
|
140
|
+
}));
|
|
141
|
+
return rankInputs(inputs, terms)[0] as RankedTextPassage | undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function focusedWindow(text: string, focus: string, maxCharacters: number): string | undefined {
|
|
145
|
+
const strongest = strongestTextPassage(text, focus);
|
|
146
|
+
if (!strongest) return undefined;
|
|
147
|
+
const center = Math.floor((strongest.passage.start + strongest.passage.end) / 2);
|
|
148
|
+
const proposedStart = Math.max(0, Math.min(center - Math.floor(maxCharacters / 2), text.length - maxCharacters));
|
|
149
|
+
const previousLineBreak = proposedStart > 0 ? text.lastIndexOf("\n", proposedStart - 1) : -1;
|
|
150
|
+
const start = previousLineBreak >= 0 ? previousLineBreak + 1 : proposedStart;
|
|
151
|
+
const proposedEnd = Math.min(text.length, start + maxCharacters);
|
|
152
|
+
const previousEndLineBreak = proposedEnd < text.length ? text.lastIndexOf("\n", proposedEnd) : -1;
|
|
153
|
+
const end = previousEndLineBreak > start ? previousEndLineBreak + 1 : proposedEnd;
|
|
154
|
+
return text.slice(start, end);
|
|
155
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { FreeflowContextRuntime } from "../freeflow-context/runtime.js";
|
|
2
|
+
import { contextRefForEntry, entryIdFromContextRef } from "../freeflow-context/types.js";
|
|
3
|
+
import type { FreeflowContextSnapshot, ProjectedContextSource } from "../freeflow-context/types.js";
|
|
4
|
+
import { focusedWindow } from "./ranking.js";
|
|
5
|
+
import { searchConversationEntries, type ConversationSearchOptions } from "./search.js";
|
|
6
|
+
import { tokenize, unique } from "./passages.js";
|
|
7
|
+
import type { ConversationSearchEntry } from "./types.js";
|
|
8
|
+
|
|
9
|
+
const MAX_QUERY_CHARACTERS = 500;
|
|
10
|
+
const MAX_QUERY_TERMS = 32;
|
|
11
|
+
const MAX_TOOL_NAMES = 8;
|
|
12
|
+
const MAX_TOOL_NAME_CHARACTERS = 128;
|
|
13
|
+
const MAX_REF_CHARACTERS = 256;
|
|
14
|
+
const MAX_FOCUS_CHARACTERS = 500;
|
|
15
|
+
const MAX_RETRIEVE_REFS = 3;
|
|
16
|
+
const MAX_SOURCE_CHARACTERS = 8_000;
|
|
17
|
+
const MAX_TOTAL_RETRIEVED_CHARACTERS = 24_000;
|
|
18
|
+
const VALID_KINDS = new Set(["user", "assistant", "toolResult", "summary"]);
|
|
19
|
+
|
|
20
|
+
function normalizedTerms(value: string): string[] {
|
|
21
|
+
return unique(tokenize(value));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function failure(operation: "search" | "retrieve", reason: string, message?: string) {
|
|
25
|
+
return {
|
|
26
|
+
status: "rejected" as const,
|
|
27
|
+
operation,
|
|
28
|
+
reason: reason.slice(0, 64),
|
|
29
|
+
...(message ? { message: message.slice(0, 500) } : {}),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function unavailable(operation: "search" | "retrieve", reason = "conversation_history_unavailable") {
|
|
34
|
+
return { status: "unavailable" as const, operation, reason: reason.slice(0, 64) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function sourceMetadata(source: ProjectedContextSource) {
|
|
38
|
+
return {
|
|
39
|
+
ref: source.ref,
|
|
40
|
+
kind: source.kind,
|
|
41
|
+
...(source.toolNames
|
|
42
|
+
? {
|
|
43
|
+
toolNames: source.toolNames.slice(0, MAX_TOOL_NAMES),
|
|
44
|
+
...(source.toolNames.length > MAX_TOOL_NAMES ? { toolNamesTruncated: true } : {}),
|
|
45
|
+
}
|
|
46
|
+
: {}),
|
|
47
|
+
...(source.isError === undefined ? {} : { isError: source.isError }),
|
|
48
|
+
timestamp: source.timestamp.slice(0, 64),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class ConversationHistoryRuntime {
|
|
53
|
+
private ctx: any;
|
|
54
|
+
private readonly freeflowContext: FreeflowContextRuntime;
|
|
55
|
+
private readonly isSourceFullyProjected: (entryId: string) => boolean;
|
|
56
|
+
private snapshot: FreeflowContextSnapshot | undefined;
|
|
57
|
+
private available = true;
|
|
58
|
+
private unavailableReason: string | undefined;
|
|
59
|
+
|
|
60
|
+
constructor(
|
|
61
|
+
ctx: any,
|
|
62
|
+
isSourceFullyProjected: (entryId: string) => boolean = () => true,
|
|
63
|
+
freeflowContext = new FreeflowContextRuntime(ctx),
|
|
64
|
+
) {
|
|
65
|
+
this.ctx = ctx;
|
|
66
|
+
this.isSourceFullyProjected = isSourceFullyProjected;
|
|
67
|
+
this.freeflowContext = freeflowContext;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
setContext(ctx: any): void {
|
|
71
|
+
this.ctx = ctx;
|
|
72
|
+
this.freeflowContext.setContext(ctx);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
capture(contextVirtualizationEnabled = false): boolean {
|
|
76
|
+
try {
|
|
77
|
+
this.freeflowContext.setContext(this.ctx);
|
|
78
|
+
this.snapshot = this.freeflowContext.captureSnapshot({
|
|
79
|
+
contextVirtualizationEnabled,
|
|
80
|
+
isSourceFullyProjected: this.isSourceFullyProjected,
|
|
81
|
+
});
|
|
82
|
+
this.available = true;
|
|
83
|
+
this.unavailableReason = undefined;
|
|
84
|
+
return true;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
this.snapshot = undefined;
|
|
87
|
+
this.available = false;
|
|
88
|
+
this.unavailableReason = error instanceof Error ? error.message : String(error);
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async search(params: Record<string, unknown>, signal?: AbortSignal): Promise<any> {
|
|
94
|
+
if (signal?.aborted) return unavailable("search", "conversation_history_search_cancelled");
|
|
95
|
+
if (!this.available || !this.snapshot) return unavailable("search", this.unavailableReason);
|
|
96
|
+
const validation = this.validateSearch(params);
|
|
97
|
+
if (validation) return validation;
|
|
98
|
+
|
|
99
|
+
const query = (params.query as string).trim();
|
|
100
|
+
const hidden = [...this.snapshot.entries.values()].filter(
|
|
101
|
+
(entry) =>
|
|
102
|
+
!this.snapshot?.visibleSourceIds.has(entry.source.source.entryId) &&
|
|
103
|
+
!this.snapshot?.materializedSourceIds.has(entry.source.source.entryId),
|
|
104
|
+
);
|
|
105
|
+
if (hidden.length === 0) {
|
|
106
|
+
if (this.snapshot.skippedEntries === 0) return failure("search", "no_hidden_conversation_history");
|
|
107
|
+
return {
|
|
108
|
+
status: "ok",
|
|
109
|
+
operation: "search",
|
|
110
|
+
query,
|
|
111
|
+
coverage: "partial",
|
|
112
|
+
skippedEntries: this.snapshot.skippedEntries,
|
|
113
|
+
returned: 0,
|
|
114
|
+
truncated: false,
|
|
115
|
+
hits: [],
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let result;
|
|
120
|
+
try {
|
|
121
|
+
result = searchConversationEntries(
|
|
122
|
+
hidden as ConversationSearchEntry[],
|
|
123
|
+
{
|
|
124
|
+
query,
|
|
125
|
+
kinds: params.kinds as ConversationSearchOptions["kinds"],
|
|
126
|
+
toolNames: Array.isArray(params.toolNames)
|
|
127
|
+
? params.toolNames.map((name) => (typeof name === "string" ? name.trim() : ""))
|
|
128
|
+
: undefined,
|
|
129
|
+
limit: params.limit as number | undefined,
|
|
130
|
+
},
|
|
131
|
+
signal,
|
|
132
|
+
);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) {
|
|
135
|
+
return unavailable("search", "conversation_history_search_cancelled");
|
|
136
|
+
}
|
|
137
|
+
return unavailable("search");
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
status: "ok",
|
|
141
|
+
operation: "search",
|
|
142
|
+
query,
|
|
143
|
+
coverage: this.snapshot.skippedEntries > 0 ? "partial" : "complete",
|
|
144
|
+
...(this.snapshot.skippedEntries > 0 ? { skippedEntries: this.snapshot.skippedEntries } : {}),
|
|
145
|
+
returned: result.returned,
|
|
146
|
+
truncated: result.truncated,
|
|
147
|
+
hits: result.hits,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async retrieve(params: Record<string, unknown>, signal?: AbortSignal): Promise<any> {
|
|
152
|
+
if (signal?.aborted) return unavailable("retrieve", "conversation_history_retrieve_cancelled");
|
|
153
|
+
if (!this.available || !this.snapshot) return unavailable("retrieve", this.unavailableReason);
|
|
154
|
+
const refs = params.refs;
|
|
155
|
+
if (!Array.isArray(refs) || refs.length < 1 || refs.length > MAX_RETRIEVE_REFS) {
|
|
156
|
+
return failure("retrieve", "refs_count_invalid");
|
|
157
|
+
}
|
|
158
|
+
if (refs.some((ref) => typeof ref !== "string" || ref.length > MAX_REF_CHARACTERS)) {
|
|
159
|
+
return failure("retrieve", "ref_invalid");
|
|
160
|
+
}
|
|
161
|
+
const canonicalRefs = refs.map((ref) => {
|
|
162
|
+
const entryId = entryIdFromContextRef(ref);
|
|
163
|
+
return entryId ? contextRefForEntry(entryId) : undefined;
|
|
164
|
+
});
|
|
165
|
+
if (canonicalRefs.some((ref) => ref === undefined)) return failure("retrieve", "ref_invalid");
|
|
166
|
+
const uniqueRefs = canonicalRefs as string[];
|
|
167
|
+
if (new Set(uniqueRefs).size !== uniqueRefs.length) return failure("retrieve", "duplicate_ref");
|
|
168
|
+
const focus = params.focus;
|
|
169
|
+
if (
|
|
170
|
+
focus !== undefined &&
|
|
171
|
+
(typeof focus !== "string" || focus.trim().length === 0 || focus.length > MAX_FOCUS_CHARACTERS)
|
|
172
|
+
) {
|
|
173
|
+
return failure("retrieve", "focus_invalid");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const items = [];
|
|
177
|
+
let total = 0;
|
|
178
|
+
for (const ref of uniqueRefs) {
|
|
179
|
+
if (signal?.aborted) return unavailable("retrieve", "conversation_history_retrieve_cancelled");
|
|
180
|
+
const entryId = entryIdFromContextRef(ref);
|
|
181
|
+
const source = entryId ? this.snapshot.entries.get(contextRefForEntry(entryId)) : undefined;
|
|
182
|
+
if (!source) return failure("retrieve", "reference_unresolved");
|
|
183
|
+
if (this.snapshot.visibleSourceIds.has(entryId) || this.snapshot.materializedSourceIds.has(entryId)) {
|
|
184
|
+
return failure("retrieve", "source_visible");
|
|
185
|
+
}
|
|
186
|
+
const sourceCharacters = source.text.length;
|
|
187
|
+
let content = source.text;
|
|
188
|
+
let completeness: "complete" | "partial" = "complete";
|
|
189
|
+
if (sourceCharacters > MAX_SOURCE_CHARACTERS) {
|
|
190
|
+
if (typeof focus !== "string") return failure("retrieve", "focus_required_for_oversized_source");
|
|
191
|
+
const focused = focusedWindow(source.text, focus.trim(), MAX_SOURCE_CHARACTERS);
|
|
192
|
+
if (focused === undefined) return failure("retrieve", "focus_no_match");
|
|
193
|
+
content = focused;
|
|
194
|
+
completeness = "partial";
|
|
195
|
+
}
|
|
196
|
+
if (total + content.length > MAX_TOTAL_RETRIEVED_CHARACTERS)
|
|
197
|
+
return failure("retrieve", "retrieval_budget_exceeded");
|
|
198
|
+
total += content.length;
|
|
199
|
+
items.push({
|
|
200
|
+
...sourceMetadata(source),
|
|
201
|
+
content,
|
|
202
|
+
completeness,
|
|
203
|
+
sourceCharacters,
|
|
204
|
+
returnedCharacters: content.length,
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
status: "ok",
|
|
209
|
+
operation: "retrieve",
|
|
210
|
+
...(typeof focus === "string" ? { focus: focus.trim() } : {}),
|
|
211
|
+
items,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private validateSearch(params: Record<string, unknown>): any | undefined {
|
|
216
|
+
if (typeof params.query !== "string" || params.query.trim().length === 0)
|
|
217
|
+
return failure("search", "query_required");
|
|
218
|
+
if (params.query.length > MAX_QUERY_CHARACTERS) return failure("search", "query_too_long");
|
|
219
|
+
if (normalizedTerms(params.query).length > MAX_QUERY_TERMS) return failure("search", "query_terms_too_many");
|
|
220
|
+
if (params.kinds !== undefined) {
|
|
221
|
+
if (!Array.isArray(params.kinds) || params.kinds.length < 1 || params.kinds.length > 4)
|
|
222
|
+
return failure("search", "kinds_invalid");
|
|
223
|
+
if (
|
|
224
|
+
new Set(params.kinds).size !== params.kinds.length ||
|
|
225
|
+
params.kinds.some((kind) => typeof kind !== "string" || !VALID_KINDS.has(kind))
|
|
226
|
+
) {
|
|
227
|
+
return failure("search", "kinds_invalid");
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (params.toolNames !== undefined) {
|
|
231
|
+
if (!Array.isArray(params.toolNames) || params.toolNames.length < 1 || params.toolNames.length > MAX_TOOL_NAMES)
|
|
232
|
+
return failure("search", "tool_names_invalid");
|
|
233
|
+
const normalizedNames = params.toolNames.map((name) => (typeof name === "string" ? name.trim() : ""));
|
|
234
|
+
if (
|
|
235
|
+
params.toolNames.some((name) => typeof name !== "string") ||
|
|
236
|
+
new Set(normalizedNames.map((name) => name.toLocaleLowerCase())).size !== normalizedNames.length ||
|
|
237
|
+
normalizedNames.some((name) => name.length === 0 || name.length > MAX_TOOL_NAME_CHARACTERS)
|
|
238
|
+
) {
|
|
239
|
+
return failure("search", "tool_names_invalid");
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (
|
|
243
|
+
params.limit !== undefined &&
|
|
244
|
+
(!Number.isInteger(params.limit) || (params.limit as number) < 1 || (params.limit as number) > 20)
|
|
245
|
+
) {
|
|
246
|
+
return failure("search", "limit_invalid");
|
|
247
|
+
}
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { normalizeText, snippet, throwIfAborted, tokenize, unique } from "./passages.js";
|
|
2
|
+
import { rankMatchingPassages } from "./ranking.js";
|
|
3
|
+
import type {
|
|
4
|
+
ConversationSearchEntry,
|
|
5
|
+
ConversationSearchHit,
|
|
6
|
+
ConversationSearchOptions,
|
|
7
|
+
ConversationSearchResult,
|
|
8
|
+
} from "./types.js";
|
|
9
|
+
|
|
10
|
+
export type {
|
|
11
|
+
ConversationSearchEntry,
|
|
12
|
+
ConversationSearchHit,
|
|
13
|
+
ConversationSearchOptions,
|
|
14
|
+
ConversationSearchResult,
|
|
15
|
+
} from "./types.js";
|
|
16
|
+
|
|
17
|
+
const MAX_DISPLAYED_TOOL_NAMES = 8;
|
|
18
|
+
|
|
19
|
+
function matchesFilters(entry: ConversationSearchEntry, options: ConversationSearchOptions): boolean {
|
|
20
|
+
if (options.kinds && !options.kinds.includes(entry.kind)) return false;
|
|
21
|
+
if (options.toolNames) {
|
|
22
|
+
const names = new Set((entry.toolNames ?? []).map((name) => name.toLocaleLowerCase()));
|
|
23
|
+
if (!options.toolNames.some((name) => names.has(name.toLocaleLowerCase()))) return false;
|
|
24
|
+
}
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function searchConversationEntries(
|
|
29
|
+
entries: readonly ConversationSearchEntry[],
|
|
30
|
+
options: ConversationSearchOptions,
|
|
31
|
+
signal?: AbortSignal,
|
|
32
|
+
): ConversationSearchResult {
|
|
33
|
+
throwIfAborted(signal);
|
|
34
|
+
const normalizedQuery = normalizeText(options.query);
|
|
35
|
+
const terms = unique(tokenize(options.query));
|
|
36
|
+
const limit = Math.min(20, Math.max(1, Math.trunc(options.limit ?? 8)));
|
|
37
|
+
if (!normalizedQuery || terms.length === 0) return { returned: 0, truncated: false, hits: [] };
|
|
38
|
+
|
|
39
|
+
const candidates = entries.filter((entry) => matchesFilters(entry, options));
|
|
40
|
+
const rankedPassages = rankMatchingPassages(candidates, options.query, signal);
|
|
41
|
+
const byEntry = new Map<string, (typeof rankedPassages)[number]>();
|
|
42
|
+
for (const passage of rankedPassages) {
|
|
43
|
+
throwIfAborted(signal);
|
|
44
|
+
if (!byEntry.has(passage.entry.ref)) byEntry.set(passage.entry.ref, passage);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const ranked = [...byEntry.values()];
|
|
48
|
+
const hits = ranked.slice(0, limit).map((passage) => {
|
|
49
|
+
const matchType = passage.exactPhrase
|
|
50
|
+
? "exact-phrase"
|
|
51
|
+
: passage.matchedTerms.length === terms.length
|
|
52
|
+
? "all-terms"
|
|
53
|
+
: "partial-terms";
|
|
54
|
+
return {
|
|
55
|
+
ref: passage.entry.ref,
|
|
56
|
+
kind: passage.entry.kind,
|
|
57
|
+
...(passage.entry.toolNames
|
|
58
|
+
? {
|
|
59
|
+
toolNames: passage.entry.toolNames.slice(0, MAX_DISPLAYED_TOOL_NAMES),
|
|
60
|
+
...(passage.entry.toolNames.length > MAX_DISPLAYED_TOOL_NAMES ? { toolNamesTruncated: true } : {}),
|
|
61
|
+
}
|
|
62
|
+
: {}),
|
|
63
|
+
...(passage.entry.isError === undefined ? {} : { isError: passage.entry.isError }),
|
|
64
|
+
timestamp: passage.entry.timestamp.slice(0, 64),
|
|
65
|
+
snippet: snippet(passage.passage.text, normalizedQuery, terms),
|
|
66
|
+
match: {
|
|
67
|
+
type: matchType,
|
|
68
|
+
matchedTerms: passage.matchedTerms,
|
|
69
|
+
queryTermCount: terms.length,
|
|
70
|
+
},
|
|
71
|
+
} satisfies ConversationSearchHit;
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
returned: hits.length,
|
|
76
|
+
truncated: ranked.length > limit,
|
|
77
|
+
hits,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ProjectedContextSource } from "../freeflow-context/types.js";
|
|
2
|
+
|
|
3
|
+
export type ConversationSearchEntry = ProjectedContextSource;
|
|
4
|
+
|
|
5
|
+
export type ConversationSearchOptions = {
|
|
6
|
+
query: string;
|
|
7
|
+
kinds?: readonly ConversationSearchEntry["kind"][];
|
|
8
|
+
toolNames?: readonly string[];
|
|
9
|
+
limit?: number;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type ConversationSearchHit = {
|
|
13
|
+
ref: string;
|
|
14
|
+
kind: ConversationSearchEntry["kind"];
|
|
15
|
+
toolNames?: string[];
|
|
16
|
+
toolNamesTruncated?: boolean;
|
|
17
|
+
isError?: boolean;
|
|
18
|
+
timestamp: string;
|
|
19
|
+
snippet: string;
|
|
20
|
+
match: {
|
|
21
|
+
type: "exact-phrase" | "all-terms" | "partial-terms";
|
|
22
|
+
matchedTerms: string[];
|
|
23
|
+
queryTermCount: number;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type ConversationSearchResult = {
|
|
28
|
+
returned: number;
|
|
29
|
+
truncated: boolean;
|
|
30
|
+
hits: ConversationSearchHit[];
|
|
31
|
+
};
|