@peer-agent/runtime-core 0.0.1-beta.43
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/LICENSE +21 -0
- package/README.md +26 -0
- package/dist/capability-registry.d.ts +15 -0
- package/dist/capability-registry.js +88 -0
- package/dist/compaction-progress.d.ts +51 -0
- package/dist/compaction-progress.js +83 -0
- package/dist/context-accounting-lifecycle.d.ts +41 -0
- package/dist/context-accounting-lifecycle.js +90 -0
- package/dist/context-accounting-pipeline.d.ts +98 -0
- package/dist/context-accounting-pipeline.js +561 -0
- package/dist/context-compaction.d.ts +70 -0
- package/dist/context-compaction.js +192 -0
- package/dist/context-projection-lifecycle.d.ts +32 -0
- package/dist/context-projection-lifecycle.js +65 -0
- package/dist/context-projection.d.ts +74 -0
- package/dist/context-projection.js +183 -0
- package/dist/contracts.d.ts +218 -0
- package/dist/contracts.js +1 -0
- package/dist/conversation-history-projector.d.ts +52 -0
- package/dist/conversation-history-projector.js +472 -0
- package/dist/decision.d.ts +4 -0
- package/dist/decision.js +23 -0
- package/dist/evidence.d.ts +64 -0
- package/dist/evidence.js +127 -0
- package/dist/hooks.d.ts +5 -0
- package/dist/hooks.js +4 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +18 -0
- package/dist/local-tool-contracts.d.ts +60 -0
- package/dist/local-tool-contracts.js +64 -0
- package/dist/microcompact.d.ts +38 -0
- package/dist/microcompact.js +354 -0
- package/dist/permission.d.ts +18 -0
- package/dist/permission.js +50 -0
- package/dist/projection-materializers.d.ts +18 -0
- package/dist/projection-materializers.js +34 -0
- package/dist/projection.d.ts +15 -0
- package/dist/projection.js +78 -0
- package/dist/runtime-usage-accounting.d.ts +19 -0
- package/dist/runtime-usage-accounting.js +79 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 梁音
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# @peer-agent/runtime-core
|
|
2
|
+
|
|
3
|
+
Host-neutral capability, permission, projection, and Evidence primitives for Peer Agent runtimes.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @peer-agent/runtime-core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Use it to build a capability provider registry, project host capabilities into model-visible tools, merge grants/hooks, and create/validate Evidence without depending on Electron, TUI, filesystem, or Shell implementations.
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
import { createCapabilityProviderRegistry } from '@peer-agent/runtime-core';
|
|
15
|
+
|
|
16
|
+
const registry = createCapabilityProviderRegistry();
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Boundary
|
|
20
|
+
|
|
21
|
+
- **Public:** capability/provider interfaces, projection, permission/grant logic, Evidence primitives.
|
|
22
|
+
- **Not included:** Node file/Shell adapters (`@peer-agent/runtime-node` is private), Desktop IPC, UI, model credentials.
|
|
23
|
+
|
|
24
|
+
## Version policy
|
|
25
|
+
|
|
26
|
+
Follows the repository root `VERSION` and the same release tag as protocol / runtime-sdk / CLI / Desktop during beta.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { CapabilityExecutionContext, CapabilityProvider, CapabilityRequest, CapabilityResult, RuntimeCapabilityId, RuntimeProviderId } from './contracts.ts';
|
|
2
|
+
export type CapabilityRegistryErrorCode = 'invalid_provider' | 'duplicate_provider' | 'duplicate_capability' | 'capability_not_found';
|
|
3
|
+
export declare class CapabilityRegistryError extends Error {
|
|
4
|
+
readonly code: CapabilityRegistryErrorCode;
|
|
5
|
+
constructor(message: string, code: CapabilityRegistryErrorCode);
|
|
6
|
+
}
|
|
7
|
+
export interface CapabilityProviderRegistry {
|
|
8
|
+
register(provider: CapabilityProvider): void;
|
|
9
|
+
getProvider(capabilityId: RuntimeCapabilityId): CapabilityProvider | undefined;
|
|
10
|
+
execute(request: CapabilityRequest, context: CapabilityExecutionContext): Promise<CapabilityResult>;
|
|
11
|
+
hasCapability(capabilityId: RuntimeCapabilityId): boolean;
|
|
12
|
+
listCapabilityIds(): RuntimeCapabilityId[];
|
|
13
|
+
listProviderIds(): RuntimeProviderId[];
|
|
14
|
+
}
|
|
15
|
+
export declare function createCapabilityProviderRegistry(initialProviders?: readonly CapabilityProvider[]): CapabilityProviderRegistry;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export class CapabilityRegistryError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
constructor(message, code) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = 'CapabilityRegistryError';
|
|
6
|
+
this.code = code;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
function providerCapabilityIds(provider) {
|
|
10
|
+
if (Array.isArray(provider.capabilityIds)) {
|
|
11
|
+
return provider.capabilityIds;
|
|
12
|
+
}
|
|
13
|
+
if (Array.isArray(provider.capabilities)) {
|
|
14
|
+
return provider.capabilities.map((capability) => capability.capabilityId);
|
|
15
|
+
}
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
function assertProvider(provider) {
|
|
19
|
+
if (!provider || typeof provider !== 'object') {
|
|
20
|
+
throw new CapabilityRegistryError('Capability provider must be an object.', 'invalid_provider');
|
|
21
|
+
}
|
|
22
|
+
if (!provider.providerId) {
|
|
23
|
+
throw new CapabilityRegistryError('Capability provider must declare providerId.', 'invalid_provider');
|
|
24
|
+
}
|
|
25
|
+
const hasIds = providerCapabilityIds(provider).length > 0;
|
|
26
|
+
const hasPrefix = typeof provider.capabilityPrefix === 'string' && provider.capabilityPrefix.length > 0;
|
|
27
|
+
const hasCanHandle = typeof provider.canHandle === 'function';
|
|
28
|
+
if (!hasIds && !hasPrefix && !hasCanHandle) {
|
|
29
|
+
throw new CapabilityRegistryError('Capability provider must declare capabilityIds, capabilities, capabilityPrefix, or canHandle().', 'invalid_provider');
|
|
30
|
+
}
|
|
31
|
+
if (typeof provider.execute !== 'function') {
|
|
32
|
+
throw new CapabilityRegistryError('Capability provider must implement execute().', 'invalid_provider');
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function createCapabilityProviderRegistry(initialProviders = []) {
|
|
36
|
+
const providersById = new Map();
|
|
37
|
+
const providerByCapabilityId = new Map();
|
|
38
|
+
const prefixProviders = [];
|
|
39
|
+
const customProviders = [];
|
|
40
|
+
function register(provider) {
|
|
41
|
+
assertProvider(provider);
|
|
42
|
+
if (providersById.has(provider.providerId)) {
|
|
43
|
+
throw new CapabilityRegistryError(`Duplicate capability provider: ${provider.providerId}`, 'duplicate_provider');
|
|
44
|
+
}
|
|
45
|
+
providersById.set(provider.providerId, provider);
|
|
46
|
+
for (const capabilityId of providerCapabilityIds(provider)) {
|
|
47
|
+
if (providerByCapabilityId.has(capabilityId)) {
|
|
48
|
+
throw new CapabilityRegistryError(`Duplicate capability id: ${capabilityId}`, 'duplicate_capability');
|
|
49
|
+
}
|
|
50
|
+
providerByCapabilityId.set(capabilityId, provider);
|
|
51
|
+
}
|
|
52
|
+
if (provider.capabilityPrefix) {
|
|
53
|
+
prefixProviders.push(provider);
|
|
54
|
+
}
|
|
55
|
+
if (provider.canHandle) {
|
|
56
|
+
customProviders.push(provider);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function getProvider(capabilityId) {
|
|
60
|
+
const direct = providerByCapabilityId.get(capabilityId);
|
|
61
|
+
if (direct) {
|
|
62
|
+
return direct;
|
|
63
|
+
}
|
|
64
|
+
const prefixed = prefixProviders.find((provider) => capabilityId.startsWith(provider.capabilityPrefix ?? ''));
|
|
65
|
+
if (prefixed) {
|
|
66
|
+
return prefixed;
|
|
67
|
+
}
|
|
68
|
+
return customProviders.find((provider) => provider.canHandle?.(capabilityId));
|
|
69
|
+
}
|
|
70
|
+
async function execute(request, context) {
|
|
71
|
+
const provider = getProvider(request.capabilityId);
|
|
72
|
+
if (!provider) {
|
|
73
|
+
throw new CapabilityRegistryError(`No capability provider found for ${request.capabilityId}`, 'capability_not_found');
|
|
74
|
+
}
|
|
75
|
+
return provider.execute(request, context);
|
|
76
|
+
}
|
|
77
|
+
for (const provider of initialProviders) {
|
|
78
|
+
register(provider);
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
register,
|
|
82
|
+
getProvider,
|
|
83
|
+
execute,
|
|
84
|
+
hasCapability: (capabilityId) => Boolean(getProvider(capabilityId)),
|
|
85
|
+
listCapabilityIds: () => [...providerByCapabilityId.keys()],
|
|
86
|
+
listProviderIds: () => [...providersById.keys()],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared compaction UI progress estimator.
|
|
3
|
+
*
|
|
4
|
+
* percent = receivedChars / estimateSummaryChars(...)
|
|
5
|
+
* This is the single source for Desktop banner + CLI/TUI compacting status.
|
|
6
|
+
*/
|
|
7
|
+
export declare const COMPACTION_PROGRESS_CONFIG: Readonly<{
|
|
8
|
+
summaryCompressionRatio: 0.12;
|
|
9
|
+
minEstimatedSummaryChars: 1200;
|
|
10
|
+
expandFactor: 1.05;
|
|
11
|
+
maxLivePercent: 99;
|
|
12
|
+
defaultMaxSummaryChars: number;
|
|
13
|
+
stageStartedPercent: 8;
|
|
14
|
+
stagePreparedPercent: 15;
|
|
15
|
+
stagePostProcessPercent: 99;
|
|
16
|
+
}>;
|
|
17
|
+
export type EstimateSummaryCharsInput = Readonly<{
|
|
18
|
+
inputChars: number;
|
|
19
|
+
maxSummaryChars: number;
|
|
20
|
+
receivedChars?: number;
|
|
21
|
+
}>;
|
|
22
|
+
/**
|
|
23
|
+
* Estimate the summary output length used as the progress bar denominator.
|
|
24
|
+
*
|
|
25
|
+
* - base = inputChars × summaryCompressionRatio
|
|
26
|
+
* - clamp to [minEstimatedSummaryChars, maxSummaryChars]
|
|
27
|
+
* - if receivedChars approaches/overshoots the estimate, expand the denominator
|
|
28
|
+
* so percent stays monotonic and does not hit 100% before done
|
|
29
|
+
*/
|
|
30
|
+
export declare function estimateSummaryChars(input: EstimateSummaryCharsInput): number;
|
|
31
|
+
export type EstimateCompactionProgressPercentInput = Readonly<{
|
|
32
|
+
inputChars: number;
|
|
33
|
+
maxSummaryChars: number;
|
|
34
|
+
receivedChars: number;
|
|
35
|
+
/** When true, always return 100. */
|
|
36
|
+
done?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Optional floor so pre-stream stage markers (started/prepared) do not
|
|
39
|
+
* regress when the first streamed chars produce a lower percent.
|
|
40
|
+
*/
|
|
41
|
+
minPercent?: number;
|
|
42
|
+
}>;
|
|
43
|
+
/**
|
|
44
|
+
* Convert received/estimated summary chars into a 0–100 UI percent.
|
|
45
|
+
* Live progress is capped at maxLivePercent; only `done` returns 100.
|
|
46
|
+
*/
|
|
47
|
+
export declare function estimateCompactionProgressPercent(input: EstimateCompactionProgressPercentInput): number;
|
|
48
|
+
export declare function resolveMaxSummaryChars(input?: {
|
|
49
|
+
maxOutputTokens?: number | null;
|
|
50
|
+
charsPerToken?: number;
|
|
51
|
+
}): number;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { CONTEXT_PROJECTION_CONFIG } from "./context-projection.js";
|
|
2
|
+
/**
|
|
3
|
+
* Shared compaction UI progress estimator.
|
|
4
|
+
*
|
|
5
|
+
* percent = receivedChars / estimateSummaryChars(...)
|
|
6
|
+
* This is the single source for Desktop banner + CLI/TUI compacting status.
|
|
7
|
+
*/
|
|
8
|
+
export const COMPACTION_PROGRESS_CONFIG = Object.freeze({
|
|
9
|
+
// Semantic summary length ≈ input length × compression ratio.
|
|
10
|
+
summaryCompressionRatio: 0.12,
|
|
11
|
+
// Floor so tiny inputs do not instantly fill the bar.
|
|
12
|
+
minEstimatedSummaryChars: 1_200,
|
|
13
|
+
// When received approaches/overshoots the estimate, expand the denominator.
|
|
14
|
+
expandFactor: 1.05,
|
|
15
|
+
// Live streaming never reports 100%; only the done signal does.
|
|
16
|
+
maxLivePercent: 99,
|
|
17
|
+
// Fallback physical cap when caller omits maxSummaryChars.
|
|
18
|
+
defaultMaxSummaryChars: 12_000 * CONTEXT_PROJECTION_CONFIG.charsPerToken,
|
|
19
|
+
// Soft stage floors used before any summary tokens arrive.
|
|
20
|
+
stageStartedPercent: 8,
|
|
21
|
+
stagePreparedPercent: 15,
|
|
22
|
+
stagePostProcessPercent: 99,
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* Estimate the summary output length used as the progress bar denominator.
|
|
26
|
+
*
|
|
27
|
+
* - base = inputChars × summaryCompressionRatio
|
|
28
|
+
* - clamp to [minEstimatedSummaryChars, maxSummaryChars]
|
|
29
|
+
* - if receivedChars approaches/overshoots the estimate, expand the denominator
|
|
30
|
+
* so percent stays monotonic and does not hit 100% before done
|
|
31
|
+
*/
|
|
32
|
+
export function estimateSummaryChars(input) {
|
|
33
|
+
const safeInput = Number.isFinite(input.inputChars) && input.inputChars > 0 ? input.inputChars : 0;
|
|
34
|
+
const minChars = COMPACTION_PROGRESS_CONFIG.minEstimatedSummaryChars;
|
|
35
|
+
const upperBound = Number.isFinite(input.maxSummaryChars) && input.maxSummaryChars > minChars
|
|
36
|
+
? input.maxSummaryChars
|
|
37
|
+
: Math.max(minChars, COMPACTION_PROGRESS_CONFIG.defaultMaxSummaryChars);
|
|
38
|
+
let estimate = Math.round(safeInput * COMPACTION_PROGRESS_CONFIG.summaryCompressionRatio);
|
|
39
|
+
estimate = Math.min(upperBound, Math.max(minChars, estimate));
|
|
40
|
+
const receivedChars = Number.isFinite(input.receivedChars) && (input.receivedChars ?? 0) > 0
|
|
41
|
+
? Number(input.receivedChars)
|
|
42
|
+
: 0;
|
|
43
|
+
if (receivedChars > 0) {
|
|
44
|
+
const expanded = Math.ceil(receivedChars * COMPACTION_PROGRESS_CONFIG.expandFactor);
|
|
45
|
+
estimate = Math.min(upperBound, Math.max(estimate, expanded));
|
|
46
|
+
}
|
|
47
|
+
return Math.max(minChars, estimate);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Convert received/estimated summary chars into a 0–100 UI percent.
|
|
51
|
+
* Live progress is capped at maxLivePercent; only `done` returns 100.
|
|
52
|
+
*/
|
|
53
|
+
export function estimateCompactionProgressPercent(input) {
|
|
54
|
+
if (input.done)
|
|
55
|
+
return 100;
|
|
56
|
+
const received = Number.isFinite(input.receivedChars) && input.receivedChars > 0 ? input.receivedChars : 0;
|
|
57
|
+
if (received <= 0) {
|
|
58
|
+
const floor = typeof input.minPercent === 'number' && Number.isFinite(input.minPercent)
|
|
59
|
+
? Math.max(0, Math.min(COMPACTION_PROGRESS_CONFIG.maxLivePercent, Math.round(input.minPercent)))
|
|
60
|
+
: 0;
|
|
61
|
+
return floor;
|
|
62
|
+
}
|
|
63
|
+
const estimatedTotalChars = estimateSummaryChars({
|
|
64
|
+
inputChars: input.inputChars,
|
|
65
|
+
maxSummaryChars: input.maxSummaryChars,
|
|
66
|
+
receivedChars: received,
|
|
67
|
+
});
|
|
68
|
+
const total = estimatedTotalChars > 0 ? estimatedTotalChars : 1;
|
|
69
|
+
let percent = Math.min(COMPACTION_PROGRESS_CONFIG.maxLivePercent, Math.round((received / total) * 100));
|
|
70
|
+
if (typeof input.minPercent === 'number' && Number.isFinite(input.minPercent)) {
|
|
71
|
+
percent = Math.max(Math.max(0, Math.min(COMPACTION_PROGRESS_CONFIG.maxLivePercent, Math.round(input.minPercent))), percent);
|
|
72
|
+
}
|
|
73
|
+
return percent;
|
|
74
|
+
}
|
|
75
|
+
export function resolveMaxSummaryChars(input) {
|
|
76
|
+
const charsPerToken = Number.isFinite(input?.charsPerToken) && (input?.charsPerToken ?? 0) > 0
|
|
77
|
+
? Number(input?.charsPerToken)
|
|
78
|
+
: CONTEXT_PROJECTION_CONFIG.charsPerToken;
|
|
79
|
+
const maxOutputTokens = Number.isFinite(input?.maxOutputTokens) && (input?.maxOutputTokens ?? 0) > 0
|
|
80
|
+
? Number(input?.maxOutputTokens)
|
|
81
|
+
: 12_000;
|
|
82
|
+
return Math.max(COMPACTION_PROGRESS_CONFIG.minEstimatedSummaryChars, Math.round(maxOutputTokens * charsPerToken));
|
|
83
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ContextAccountingPhase, ContextAccountingSnapshot, ContextCountCapability } from '@peer-agent/protocol';
|
|
2
|
+
export type ContextAccountingIdentity = Readonly<{
|
|
3
|
+
conversationId: string;
|
|
4
|
+
contentRevision: number;
|
|
5
|
+
modelKey: string;
|
|
6
|
+
}>;
|
|
7
|
+
export type ContextAccountingLifecycle = Readonly<{
|
|
8
|
+
stable(snapshot: ContextAccountingSnapshot, phase?: ContextAccountingPhase, options?: Readonly<{
|
|
9
|
+
pendingUncountedChanges?: boolean;
|
|
10
|
+
pendingContentChars?: number;
|
|
11
|
+
}>): ContextAccountingSnapshot;
|
|
12
|
+
streamPreview(delta: string): ContextAccountingSnapshot;
|
|
13
|
+
markPending(phase: ContextAccountingPhase, addedContentChars?: number): ContextAccountingSnapshot;
|
|
14
|
+
invalidateModel(input: Readonly<{
|
|
15
|
+
identity: ContextAccountingIdentity;
|
|
16
|
+
contextWindow: number | null;
|
|
17
|
+
countCapability: ContextCountCapability;
|
|
18
|
+
}>): ContextAccountingSnapshot;
|
|
19
|
+
current(): ContextAccountingSnapshot;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function createUnknownContextAccountingSnapshot(input: Readonly<{
|
|
22
|
+
identity: ContextAccountingIdentity;
|
|
23
|
+
contextWindow: number | null;
|
|
24
|
+
countCapability: ContextCountCapability;
|
|
25
|
+
phase?: ContextAccountingPhase;
|
|
26
|
+
revision?: number;
|
|
27
|
+
compactionEpoch?: number;
|
|
28
|
+
pendingUncountedChanges?: boolean;
|
|
29
|
+
now?: number;
|
|
30
|
+
}>): ContextAccountingSnapshot;
|
|
31
|
+
export declare function isContextAccountingSnapshotCurrent(snapshot: ContextAccountingSnapshot | null | undefined, identity: ContextAccountingIdentity): snapshot is ContextAccountingSnapshot;
|
|
32
|
+
/**
|
|
33
|
+
* Owns accounting revision order and pending-content transitions for one host
|
|
34
|
+
* turn. Both Desktop and TUI publish this exact snapshot; presentation never
|
|
35
|
+
* estimates or merges token counts.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createContextAccountingLifecycle(input: Readonly<{
|
|
38
|
+
initialSnapshot: ContextAccountingSnapshot;
|
|
39
|
+
onSnapshot?: (snapshot: ContextAccountingSnapshot) => void;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
}>): ContextAccountingLifecycle;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
function nonNegativeInteger(value) {
|
|
2
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
3
|
+
? Math.floor(value)
|
|
4
|
+
: 0;
|
|
5
|
+
}
|
|
6
|
+
function normalizeWindow(value) {
|
|
7
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
8
|
+
? Math.floor(value)
|
|
9
|
+
: null;
|
|
10
|
+
}
|
|
11
|
+
export function createUnknownContextAccountingSnapshot(input) {
|
|
12
|
+
const contextWindow = normalizeWindow(input.contextWindow);
|
|
13
|
+
return Object.freeze({
|
|
14
|
+
version: 1,
|
|
15
|
+
conversationId: input.identity.conversationId,
|
|
16
|
+
contentRevision: nonNegativeInteger(input.identity.contentRevision),
|
|
17
|
+
modelKey: input.identity.modelKey,
|
|
18
|
+
revision: nonNegativeInteger(input.revision),
|
|
19
|
+
phase: input.phase ?? 'restored',
|
|
20
|
+
compactionEpoch: nonNegativeInteger(input.compactionEpoch),
|
|
21
|
+
contextWindow,
|
|
22
|
+
inputBudget: contextWindow,
|
|
23
|
+
compactionThresholdTokens: contextWindow == null
|
|
24
|
+
? null
|
|
25
|
+
: Math.floor(contextWindow * 0.8),
|
|
26
|
+
authoritativeInputTokens: null,
|
|
27
|
+
percent: null,
|
|
28
|
+
pressureSource: 'unknown',
|
|
29
|
+
pendingUncountedChanges: input.pendingUncountedChanges ?? false,
|
|
30
|
+
pendingContentChars: 0,
|
|
31
|
+
countCapability: input.countCapability,
|
|
32
|
+
counterStatus: 'active',
|
|
33
|
+
updatedAt: input.now ?? Date.now(),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
export function isContextAccountingSnapshotCurrent(snapshot, identity) {
|
|
37
|
+
return Boolean(snapshot
|
|
38
|
+
&& snapshot.version === 1
|
|
39
|
+
&& snapshot.conversationId === identity.conversationId
|
|
40
|
+
&& snapshot.contentRevision === identity.contentRevision
|
|
41
|
+
&& snapshot.modelKey === identity.modelKey);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Owns accounting revision order and pending-content transitions for one host
|
|
45
|
+
* turn. Both Desktop and TUI publish this exact snapshot; presentation never
|
|
46
|
+
* estimates or merges token counts.
|
|
47
|
+
*/
|
|
48
|
+
export function createContextAccountingLifecycle(input) {
|
|
49
|
+
const now = input.now ?? Date.now;
|
|
50
|
+
let revision = nonNegativeInteger(input.initialSnapshot.revision);
|
|
51
|
+
let snapshot = input.initialSnapshot;
|
|
52
|
+
const publish = (base, phase, pendingUncountedChanges, pendingContentChars) => {
|
|
53
|
+
snapshot = Object.freeze({
|
|
54
|
+
...base,
|
|
55
|
+
revision: ++revision,
|
|
56
|
+
phase,
|
|
57
|
+
pendingUncountedChanges,
|
|
58
|
+
pendingContentChars: nonNegativeInteger(pendingContentChars),
|
|
59
|
+
updatedAt: now(),
|
|
60
|
+
});
|
|
61
|
+
input.onSnapshot?.(snapshot);
|
|
62
|
+
return snapshot;
|
|
63
|
+
};
|
|
64
|
+
const markPending = (phase, addedContentChars = 0) => publish(snapshot, phase, true, snapshot.pendingContentChars + nonNegativeInteger(addedContentChars));
|
|
65
|
+
return Object.freeze({
|
|
66
|
+
stable(base, phase = base.phase, options = {}) {
|
|
67
|
+
return publish(base, phase, options.pendingUncountedChanges ?? base.pendingUncountedChanges, options.pendingContentChars
|
|
68
|
+
?? (base.pendingUncountedChanges ? base.pendingContentChars : 0));
|
|
69
|
+
},
|
|
70
|
+
streamPreview(delta) {
|
|
71
|
+
return markPending('stream_preview', typeof delta === 'string' ? delta.length : 0);
|
|
72
|
+
},
|
|
73
|
+
markPending,
|
|
74
|
+
invalidateModel(next) {
|
|
75
|
+
const unknown = createUnknownContextAccountingSnapshot({
|
|
76
|
+
identity: next.identity,
|
|
77
|
+
contextWindow: next.contextWindow,
|
|
78
|
+
countCapability: next.countCapability,
|
|
79
|
+
phase: 'model_changed',
|
|
80
|
+
revision,
|
|
81
|
+
pendingUncountedChanges: snapshot.pendingUncountedChanges,
|
|
82
|
+
now: now(),
|
|
83
|
+
});
|
|
84
|
+
return publish(unknown, 'model_changed', unknown.pendingUncountedChanges, 0);
|
|
85
|
+
},
|
|
86
|
+
current() {
|
|
87
|
+
return snapshot;
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { ContextAccountingPhase, ContextAccountingSnapshot, ContextCountCapability, ContextOverflowEvidence } from '@peer-agent/protocol';
|
|
2
|
+
import { type CompactionDecision } from './context-projection.ts';
|
|
3
|
+
import type { ContextAccountingIdentity } from './context-accounting-lifecycle.ts';
|
|
4
|
+
export type { ContextAccountingSnapshot, ContextCountCapability, ContextOverflowEvidence, } from '@peer-agent/protocol';
|
|
5
|
+
export type ObservedUsageInput = Readonly<{
|
|
6
|
+
inputTokens?: number | null;
|
|
7
|
+
outputTokens?: number | null;
|
|
8
|
+
totalTokens?: number | null;
|
|
9
|
+
cacheReadTokens?: number | null;
|
|
10
|
+
cacheWriteTokens?: number | null;
|
|
11
|
+
requestFingerprint?: string;
|
|
12
|
+
compactionEpoch?: number;
|
|
13
|
+
observedAt?: number;
|
|
14
|
+
/**
|
|
15
|
+
* Some providers report cached input as a subset of inputTokens. Existing Peer
|
|
16
|
+
* adapters normalize cache as a separate amount, so false is the safe default.
|
|
17
|
+
*/
|
|
18
|
+
inputIncludesCache?: boolean;
|
|
19
|
+
}>;
|
|
20
|
+
export type ExactCountResult = Readonly<{
|
|
21
|
+
inputTokens: number;
|
|
22
|
+
source: 'provider_count_api' | 'provider_tokenizer';
|
|
23
|
+
}>;
|
|
24
|
+
export type ContextCompactionReason = 'observed_threshold' | 'exact_count_threshold' | 'manual' | 'forced' | 'provider_overflow';
|
|
25
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
26
|
+
type CompactResult<TState> = Readonly<{
|
|
27
|
+
compacted: boolean;
|
|
28
|
+
state: TState;
|
|
29
|
+
}>;
|
|
30
|
+
export type ContextAccountingPipelineOptions<TState, TRequest, TResponse> = Readonly<{
|
|
31
|
+
identity: ContextAccountingIdentity | (() => ContextAccountingIdentity);
|
|
32
|
+
contextWindow: number | null | undefined | (() => number | null | undefined);
|
|
33
|
+
requiredOutputReserveTokens?: number;
|
|
34
|
+
compactionThresholdRatio?: number;
|
|
35
|
+
countCapability?: ContextCountCapability;
|
|
36
|
+
initialSnapshot?: ContextAccountingSnapshot | null;
|
|
37
|
+
driftToleranceRatio?: number;
|
|
38
|
+
onSnapshot?: (snapshot: ContextAccountingSnapshot, phase: ContextAccountingPhase) => void;
|
|
39
|
+
buildRequest: (state: TState) => MaybePromise<TRequest>;
|
|
40
|
+
countRequest?: (request: TRequest) => MaybePromise<ExactCountResult | number | null | undefined>;
|
|
41
|
+
compact: (input: Readonly<{
|
|
42
|
+
state: TState;
|
|
43
|
+
reason: ContextCompactionReason;
|
|
44
|
+
emergency: boolean;
|
|
45
|
+
compactionEpoch: number;
|
|
46
|
+
}>) => MaybePromise<CompactResult<TState>>;
|
|
47
|
+
send: (request: TRequest) => Promise<TResponse>;
|
|
48
|
+
getUsage?: (response: TResponse) => ObservedUsageInput | null | undefined;
|
|
49
|
+
onProviderRequest?: (event: Readonly<{
|
|
50
|
+
requestFingerprint: string;
|
|
51
|
+
usage: ObservedUsageInput | null;
|
|
52
|
+
response?: TResponse;
|
|
53
|
+
error?: unknown;
|
|
54
|
+
}>) => void;
|
|
55
|
+
getOverflow?: (response: TResponse) => ContextOverflowEvidence | null | undefined;
|
|
56
|
+
fingerprintRequest?: (request: TRequest) => string;
|
|
57
|
+
now?: () => number;
|
|
58
|
+
}>;
|
|
59
|
+
export type ContextAccountingExecuteInput<TState> = Readonly<{
|
|
60
|
+
state: TState;
|
|
61
|
+
forceCompact?: boolean;
|
|
62
|
+
command?: 'send' | 'manual_compact' | 'count_only';
|
|
63
|
+
}>;
|
|
64
|
+
export type ContextAccountingExecuteResult<TState, TRequest, TResponse> = Readonly<{
|
|
65
|
+
state: TState;
|
|
66
|
+
request: TRequest;
|
|
67
|
+
response: TResponse | null;
|
|
68
|
+
snapshot: ContextAccountingSnapshot;
|
|
69
|
+
decision: CompactionDecision | null;
|
|
70
|
+
compactionEpoch: number;
|
|
71
|
+
compacted: boolean;
|
|
72
|
+
retriedAfterOverflow: boolean;
|
|
73
|
+
}>;
|
|
74
|
+
export declare function normalizeObservedInputTokens(usage: ObservedUsageInput | null | undefined): number | null;
|
|
75
|
+
/**
|
|
76
|
+
* Restores the last provider-backed baseline for observed-only channels.
|
|
77
|
+
*
|
|
78
|
+
* The restored number describes the last request actually measured by the
|
|
79
|
+
* provider. It remains marked pending because the assistant response and any
|
|
80
|
+
* later durable changes have not yet been measured as the next request.
|
|
81
|
+
*/
|
|
82
|
+
export declare function createRestoredObservedContextAccountingSnapshot(input: Readonly<{
|
|
83
|
+
identity: ContextAccountingIdentity;
|
|
84
|
+
contextWindow: number | null | undefined;
|
|
85
|
+
countCapability: ContextCountCapability;
|
|
86
|
+
usage: ObservedUsageInput | null | undefined;
|
|
87
|
+
revision?: number;
|
|
88
|
+
compactionEpoch?: number;
|
|
89
|
+
pendingUncountedChanges?: boolean;
|
|
90
|
+
now?: number;
|
|
91
|
+
}>): ContextAccountingSnapshot;
|
|
92
|
+
export declare function fingerprintCanonicalRequest(request: unknown): string;
|
|
93
|
+
export declare function parseContextOverflowEvidence(error: unknown): ContextOverflowEvidence | null;
|
|
94
|
+
export declare function createContextAccountingCompactionPipeline<TState, TRequest, TResponse>(options: ContextAccountingPipelineOptions<TState, TRequest, TResponse>): Readonly<{
|
|
95
|
+
execute: (input: ContextAccountingExecuteInput<TState>) => Promise<ContextAccountingExecuteResult<TState, TRequest, TResponse>>;
|
|
96
|
+
snapshot: () => ContextAccountingSnapshot;
|
|
97
|
+
observe: (usage: ObservedUsageInput | null | undefined, requestFingerprint: string, verifyCount?: boolean) => void;
|
|
98
|
+
}>;
|