@peer-agent/runtime-core 0.0.5 → 0.0.7

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/README.md CHANGED
@@ -8,12 +8,17 @@ Host-neutral capability, permission, projection, and Evidence primitives for Pee
8
8
  npm install @peer-agent/runtime-core
9
9
  ```
10
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.
11
+ Use it to build a capability provider registry, project host capabilities into model-visible tools, merge grants/hooks, pack already-admitted Evidence for export, and create/validate Evidence without depending on Electron, TUI, filesystem, or Shell implementations.
12
12
 
13
13
  ```js
14
- import { createCapabilityProviderRegistry } from '@peer-agent/runtime-core';
14
+ import {
15
+ createCapabilityProviderRegistry,
16
+ createEvidenceExportDocument,
17
+ } from '@peer-agent/runtime-core';
15
18
 
16
19
  const registry = createCapabilityProviderRegistry();
20
+ registry.register(provider);
21
+ registry.replace(nextProvider);
17
22
  ```
18
23
 
19
24
  ## Boundary
@@ -6,6 +6,8 @@ export declare class CapabilityRegistryError extends Error {
6
6
  }
7
7
  export interface CapabilityProviderRegistry {
8
8
  register(provider: CapabilityProvider): void;
9
+ unregister(providerId: RuntimeProviderId): boolean;
10
+ replace(provider: CapabilityProvider): void;
9
11
  getProvider(capabilityId: RuntimeCapabilityId): CapabilityProvider | undefined;
10
12
  execute(request: CapabilityRequest, context: CapabilityExecutionContext): Promise<CapabilityResult>;
11
13
  hasCapability(capabilityId: RuntimeCapabilityId): boolean;
@@ -56,6 +56,29 @@ export function createCapabilityProviderRegistry(initialProviders = []) {
56
56
  customProviders.push(provider);
57
57
  }
58
58
  }
59
+ function unregister(providerId) {
60
+ const existing = providersById.get(providerId);
61
+ if (!existing)
62
+ return false;
63
+ providersById.delete(providerId);
64
+ for (const capabilityId of providerCapabilityIds(existing)) {
65
+ if (providerByCapabilityId.get(capabilityId) === existing) {
66
+ providerByCapabilityId.delete(capabilityId);
67
+ }
68
+ }
69
+ const prefixIndex = prefixProviders.indexOf(existing);
70
+ if (prefixIndex >= 0)
71
+ prefixProviders.splice(prefixIndex, 1);
72
+ const customIndex = customProviders.indexOf(existing);
73
+ if (customIndex >= 0)
74
+ customProviders.splice(customIndex, 1);
75
+ return true;
76
+ }
77
+ function replace(provider) {
78
+ assertProvider(provider);
79
+ unregister(provider.providerId);
80
+ register(provider);
81
+ }
59
82
  function getProvider(capabilityId) {
60
83
  const direct = providerByCapabilityId.get(capabilityId);
61
84
  if (direct) {
@@ -79,6 +102,8 @@ export function createCapabilityProviderRegistry(initialProviders = []) {
79
102
  }
80
103
  return {
81
104
  register,
105
+ unregister,
106
+ replace,
82
107
  getProvider,
83
108
  execute,
84
109
  hasCapability: (capabilityId) => Boolean(getProvider(capabilityId)),
@@ -1,4 +1,5 @@
1
1
  import { CONTEXT_PROJECTION_CONFIG, decideContextCompaction, isPromptTooLongError, } from "./context-projection.js";
2
+ import { composeContextUsageBreakdownFromRequest, retainContextUsageBreakdown, } from "./context-usage-breakdown.js";
2
3
  function finiteTokenCount(value) {
3
4
  return typeof value === 'number' && Number.isFinite(value) && value > 0
4
5
  ? Math.floor(value)
@@ -217,6 +218,8 @@ export function createContextAccountingCompactionPipeline(options) {
217
218
  let revision = initial?.revision ?? 0;
218
219
  let phase = initial?.phase ?? 'restored';
219
220
  let latestBuiltFingerprint = null;
221
+ let latestBuiltRequest = null;
222
+ let lastUsageBreakdown = retainContextUsageBreakdown(initial?.usageBreakdown);
220
223
  const contextWindow = () => finiteWindow(typeof options.contextWindow === 'function' ? options.contextWindow() : options.contextWindow);
221
224
  const buildSnapshot = () => {
222
225
  const currentIdentity = identity();
@@ -250,6 +253,11 @@ export function createContextAccountingCompactionPipeline(options) {
250
253
  const authoritativeInputTokens = authority?.inputTokens ?? activeOverflowTokens;
251
254
  const pressureSource = authority?.source
252
255
  ?? (activeOverflowTokens ? 'provider_error_evidence' : 'unknown');
256
+ const composedBreakdown = latestBuiltRequest
257
+ ? composeContextUsageBreakdownFromRequest(latestBuiltRequest, authoritativeInputTokens)
258
+ : null;
259
+ if (composedBreakdown)
260
+ lastUsageBreakdown = composedBreakdown;
253
261
  return {
254
262
  version: 1,
255
263
  conversationId: currentIdentity.conversationId,
@@ -276,6 +284,7 @@ export function createContextAccountingCompactionPipeline(options) {
276
284
  ...(activeCounted ? { nextCounted: activeCounted } : {}),
277
285
  ...(lastOverflow ? { lastOverflow } : {}),
278
286
  ...(verification ? { verification } : {}),
287
+ ...(lastUsageBreakdown ? { usageBreakdown: lastUsageBreakdown } : {}),
279
288
  };
280
289
  };
281
290
  const publish = (nextPhase) => {
@@ -360,6 +369,7 @@ export function createContextAccountingCompactionPipeline(options) {
360
369
  const requestFingerprint = fingerprint(request);
361
370
  await count(request, requestFingerprint);
362
371
  latestBuiltFingerprint = requestFingerprint;
372
+ latestBuiltRequest = request;
363
373
  return { request, requestFingerprint };
364
374
  };
365
375
  const decide = () => {
@@ -0,0 +1,29 @@
1
+ import { type ContextUsageBreakdown } from '@peer-agent/protocol';
2
+ export type ContextUsageSectionLike = Readonly<{
3
+ readonly id?: unknown;
4
+ readonly layer?: unknown;
5
+ readonly content?: unknown;
6
+ readonly source?: unknown;
7
+ readonly sourceKind?: unknown;
8
+ }>;
9
+ export type ContextUsageMessageLike = Readonly<{
10
+ readonly role?: unknown;
11
+ readonly content?: unknown;
12
+ readonly _compaction?: unknown;
13
+ readonly toolCalls?: unknown;
14
+ readonly tool_calls?: unknown;
15
+ }>;
16
+ export type ComposeContextUsageBreakdownInput = Readonly<{
17
+ readonly systemPrompt?: string | null;
18
+ readonly systemSections?: readonly ContextUsageSectionLike[] | null;
19
+ readonly tools?: unknown;
20
+ readonly messages?: unknown;
21
+ readonly authoritativeTokens?: number | null;
22
+ }>;
23
+ /**
24
+ * Host-neutral presentation composition for the last built request.
25
+ * Renderer must display the result; it must not re-estimate occupancy.
26
+ */
27
+ export declare function composeContextUsageBreakdown(input: ComposeContextUsageBreakdownInput): ContextUsageBreakdown | null;
28
+ export declare function composeContextUsageBreakdownFromRequest(request: unknown, authoritativeTokens?: number | null): ContextUsageBreakdown | null;
29
+ export declare function retainContextUsageBreakdown(value: unknown): ContextUsageBreakdown | undefined;
@@ -0,0 +1,182 @@
1
+ import { CONTEXT_USAGE_CATEGORY_IDS, normalizeContextUsageBreakdown, } from '@peer-agent/protocol';
2
+ import { estimateContextMessagesTokens, estimateContextTextTokens, estimateContextToolsTokens, } from "./context-projection.js";
3
+ const CATEGORY_ORDER = new Map(CONTEXT_USAGE_CATEGORY_IDS.map((id, index) => [id, index]));
4
+ function isRecord(value) {
5
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
6
+ }
7
+ function haystackOf(...parts) {
8
+ return parts
9
+ .map((part) => (typeof part === 'string' ? part : ''))
10
+ .join(' ')
11
+ .toLowerCase();
12
+ }
13
+ function classifySection(section) {
14
+ const source = isRecord(section.source) ? section.source : {};
15
+ const haystack = haystackOf(section.id, section.layer, section.sourceKind, source.id, source.kind);
16
+ const layer = String(section.layer ?? '');
17
+ if (haystack.includes('mcp'))
18
+ return 'mcp_tools';
19
+ if (haystack.includes('skill'))
20
+ return 'skills';
21
+ if (haystack.includes('subagent')
22
+ || haystack.includes('explorer')
23
+ || haystack.includes('verifier')) {
24
+ return 'subagents';
25
+ }
26
+ if (layer === 'L3_INSTRUCTIONS'
27
+ || haystack.includes('instruction')
28
+ || haystack.includes('rule')) {
29
+ return 'rules';
30
+ }
31
+ if (layer === 'L7_CONTINUITY' || haystack.includes('continuity') || haystack.includes('compaction')) {
32
+ return 'summarized_conversation';
33
+ }
34
+ if (layer === 'L4_CAPABILITIES')
35
+ return 'skills';
36
+ return 'system_prompt';
37
+ }
38
+ function classifyTool(tool) {
39
+ const record = isRecord(tool) ? tool : {};
40
+ const fn = isRecord(record.function) ? record.function : {};
41
+ const runtime = isRecord(record.runtime) ? record.runtime : {};
42
+ const haystack = haystackOf(record.capabilityId, runtime.executorCapabilityId, record.name, fn.name);
43
+ if (haystack.includes('mcp'))
44
+ return 'mcp_tools';
45
+ if (haystack.includes('skill'))
46
+ return 'skills';
47
+ if (haystack.includes('subagent')
48
+ || haystack.includes('explorer')
49
+ || haystack.includes('verifier')) {
50
+ return 'subagents';
51
+ }
52
+ return 'tool_definitions';
53
+ }
54
+ function classifyMessage(message) {
55
+ if (message._compaction)
56
+ return 'summarized_conversation';
57
+ if (message.role === 'system')
58
+ return 'system_prompt';
59
+ return 'conversation';
60
+ }
61
+ function addTokens(buckets, id, tokens) {
62
+ if (!Number.isFinite(tokens) || tokens <= 0)
63
+ return;
64
+ buckets.set(id, (buckets.get(id) ?? 0) + tokens);
65
+ }
66
+ function listTools(tools) {
67
+ if (!tools)
68
+ return [];
69
+ if (Array.isArray(tools))
70
+ return tools;
71
+ if (isRecord(tools) && Array.isArray(tools.functionDeclarations)) {
72
+ return tools.functionDeclarations;
73
+ }
74
+ return [tools];
75
+ }
76
+ function listMessages(messages) {
77
+ if (!Array.isArray(messages))
78
+ return [];
79
+ return messages.filter((message) => isRecord(message));
80
+ }
81
+ function scaleBreakdown(buckets, authoritativeTokens) {
82
+ const raw = [...buckets.entries()]
83
+ .filter(([, tokens]) => tokens > 0)
84
+ .map(([id, tokens]) => [id, Math.max(1, Math.round(tokens))]);
85
+ const estimatedTokens = raw.reduce((sum, [, tokens]) => sum + tokens, 0);
86
+ if (raw.length === 0 || estimatedTokens <= 0)
87
+ return null;
88
+ const authoritative = typeof authoritativeTokens === 'number'
89
+ && Number.isFinite(authoritativeTokens)
90
+ && authoritativeTokens > 0
91
+ ? Math.floor(authoritativeTokens)
92
+ : null;
93
+ if (authoritative == null) {
94
+ return {
95
+ version: 1,
96
+ quality: 'projected',
97
+ estimatedTokens,
98
+ categories: raw
99
+ .sort((a, b) => (CATEGORY_ORDER.get(a[0]) ?? 99) - (CATEGORY_ORDER.get(b[0]) ?? 99))
100
+ .map(([id, tokens]) => ({ id, tokens })),
101
+ };
102
+ }
103
+ const scale = authoritative / estimatedTokens;
104
+ const scaled = raw.map(([id, tokens]) => [
105
+ id,
106
+ Math.max(0, Math.round(tokens * scale)),
107
+ ]);
108
+ let sum = scaled.reduce((total, [, tokens]) => total + tokens, 0);
109
+ if (sum !== authoritative && scaled.length > 0) {
110
+ let largestIndex = 0;
111
+ for (let index = 1; index < scaled.length; index += 1) {
112
+ if (scaled[index][1] > scaled[largestIndex][1])
113
+ largestIndex = index;
114
+ }
115
+ scaled[largestIndex][1] = Math.max(0, scaled[largestIndex][1] + (authoritative - sum));
116
+ sum = scaled.reduce((total, [, tokens]) => total + tokens, 0);
117
+ }
118
+ const categories = scaled
119
+ .filter(([, tokens]) => tokens > 0)
120
+ .sort((a, b) => (CATEGORY_ORDER.get(a[0]) ?? 99) - (CATEGORY_ORDER.get(b[0]) ?? 99))
121
+ .map(([id, tokens]) => ({ id, tokens }));
122
+ if (categories.length === 0)
123
+ return null;
124
+ return {
125
+ version: 1,
126
+ quality: 'scaled',
127
+ estimatedTokens: sum,
128
+ categories,
129
+ };
130
+ }
131
+ /**
132
+ * Host-neutral presentation composition for the last built request.
133
+ * Renderer must display the result; it must not re-estimate occupancy.
134
+ */
135
+ export function composeContextUsageBreakdown(input) {
136
+ const buckets = new Map();
137
+ const sections = Array.isArray(input.systemSections) ? input.systemSections : [];
138
+ if (sections.length > 0) {
139
+ for (const section of sections) {
140
+ addTokens(buckets, classifySection(section), estimateContextTextTokens(section.content));
141
+ }
142
+ }
143
+ else if (typeof input.systemPrompt === 'string' && input.systemPrompt) {
144
+ addTokens(buckets, 'system_prompt', estimateContextTextTokens(input.systemPrompt));
145
+ }
146
+ for (const tool of listTools(input.tools)) {
147
+ addTokens(buckets, classifyTool(tool), estimateContextToolsTokens([tool]));
148
+ }
149
+ for (const message of listMessages(input.messages)) {
150
+ addTokens(buckets, classifyMessage(message), estimateContextMessagesTokens([{
151
+ role: typeof message.role === 'string' ? message.role : undefined,
152
+ content: message.content,
153
+ toolCalls: Array.isArray(message.toolCalls) ? message.toolCalls : undefined,
154
+ tool_calls: Array.isArray(message.tool_calls) ? message.tool_calls : undefined,
155
+ }]));
156
+ }
157
+ return scaleBreakdown(buckets, input.authoritativeTokens);
158
+ }
159
+ export function composeContextUsageBreakdownFromRequest(request, authoritativeTokens) {
160
+ if (!isRecord(request))
161
+ return null;
162
+ const systemSections = Array.isArray(request.systemSections)
163
+ ? request.systemSections
164
+ : Array.isArray(request.systemContextSections)
165
+ ? request.systemContextSections
166
+ : null;
167
+ const systemPrompt = typeof request.systemPrompt === 'string'
168
+ ? request.systemPrompt
169
+ : typeof request.system === 'string'
170
+ ? request.system
171
+ : null;
172
+ return composeContextUsageBreakdown({
173
+ systemPrompt,
174
+ systemSections,
175
+ tools: request.tools,
176
+ messages: request.messages,
177
+ authoritativeTokens,
178
+ });
179
+ }
180
+ export function retainContextUsageBreakdown(value) {
181
+ return normalizeContextUsageBreakdown(value) ?? undefined;
182
+ }
@@ -1,4 +1,4 @@
1
- import type { EvidenceRecord, EvidenceRef, RuntimeDecision, RuntimeJsonObject } from './contracts.ts';
1
+ import type { EvidenceRecord, EvidenceRef, RuntimeCapabilityId, RuntimeDecision, RuntimeJsonObject } from './contracts.ts';
2
2
  export type EvidenceRedactor = (record: EvidenceRecord) => EvidenceRecord;
3
3
  export type RuntimeEvidenceObject = Readonly<Record<string, unknown>>;
4
4
  export interface CollectToolEvidenceRefsOptions {
@@ -53,6 +53,38 @@ export interface AppendHookEvidenceOptions {
53
53
  readonly recordedAt?: string;
54
54
  readonly now?: () => string;
55
55
  }
56
+ export declare const EVIDENCE_EXPORT_KIND = "peer.evidence.export";
57
+ export declare const EVIDENCE_EXPORT_SCHEMA_VERSION = 1;
58
+ export interface EvidenceExportSource {
59
+ readonly planId?: string;
60
+ readonly conversationId?: string;
61
+ readonly capabilityId?: RuntimeCapabilityId;
62
+ readonly toolCallId?: string;
63
+ }
64
+ export interface CreateEvidenceExportDocumentOptions {
65
+ readonly exportedAt?: string;
66
+ readonly source?: EvidenceExportSource;
67
+ readonly summary?: string;
68
+ readonly refs?: readonly EvidenceRef[];
69
+ readonly records?: readonly EvidenceRecord[];
70
+ readonly metadata?: RuntimeJsonObject;
71
+ }
72
+ export interface EvidenceExportDocument {
73
+ readonly kind: typeof EVIDENCE_EXPORT_KIND;
74
+ readonly schemaVersion: typeof EVIDENCE_EXPORT_SCHEMA_VERSION;
75
+ readonly exportedAt: string;
76
+ readonly source: EvidenceExportSource;
77
+ readonly summary?: string;
78
+ readonly refs: readonly EvidenceRef[];
79
+ readonly records: readonly EvidenceRecord[];
80
+ readonly metadata?: RuntimeJsonObject;
81
+ }
82
+ /**
83
+ * Pack already-admitted refs and records into a portable JSON document.
84
+ * This does not scan model output or enlarge the Evidence whitelist.
85
+ */
86
+ export declare function createEvidenceExportDocument(options?: CreateEvidenceExportDocumentOptions): EvidenceExportDocument;
87
+ export declare function serializeEvidenceExportDocument(document: EvidenceExportDocument): string;
56
88
  export declare function createEvidenceBundle(options?: CreateEvidenceBundleOptions): RuntimeEvidenceObject;
57
89
  export declare function applyEvidenceRedactors(record: EvidenceRecord, redactors?: readonly EvidenceRedactor[]): EvidenceRecord;
58
90
  export declare function appendEvidenceRecords<T extends {
package/dist/evidence.js CHANGED
@@ -45,6 +45,42 @@ function isEvidenceObject(value) {
45
45
  function asReadonlyArray(value) {
46
46
  return Array.isArray(value) ? value : [];
47
47
  }
48
+ export const EVIDENCE_EXPORT_KIND = 'peer.evidence.export';
49
+ export const EVIDENCE_EXPORT_SCHEMA_VERSION = 1;
50
+ /**
51
+ * Pack already-admitted refs and records into a portable JSON document.
52
+ * This does not scan model output or enlarge the Evidence whitelist.
53
+ */
54
+ export function createEvidenceExportDocument(options = {}) {
55
+ const refs = [];
56
+ const seen = new Set();
57
+ for (const ref of options.refs ?? []) {
58
+ if (typeof ref !== 'string')
59
+ continue;
60
+ const trimmed = ref.trim();
61
+ if (!trimmed || seen.has(trimmed))
62
+ continue;
63
+ seen.add(trimmed);
64
+ refs.push(trimmed);
65
+ }
66
+ const document = {
67
+ kind: EVIDENCE_EXPORT_KIND,
68
+ schemaVersion: EVIDENCE_EXPORT_SCHEMA_VERSION,
69
+ exportedAt: options.exportedAt ?? new Date().toISOString(),
70
+ source: options.source ?? {},
71
+ refs,
72
+ records: [...(options.records ?? [])],
73
+ };
74
+ const summary = typeof options.summary === 'string' ? options.summary.trim() : '';
75
+ return {
76
+ ...document,
77
+ ...(summary ? { summary } : {}),
78
+ ...(options.metadata ? { metadata: options.metadata } : {}),
79
+ };
80
+ }
81
+ export function serializeEvidenceExportDocument(document) {
82
+ return `${JSON.stringify(document, null, 2)}\n`;
83
+ }
48
84
  export function createEvidenceBundle(options = {}) {
49
85
  return {
50
86
  evidenceId: options.evidenceId,
package/dist/index.d.ts CHANGED
@@ -17,5 +17,6 @@ export * from './context-projection.ts';
17
17
  export * from './context-projection-lifecycle.ts';
18
18
  export * from './context-accounting-pipeline.ts';
19
19
  export * from './context-accounting-lifecycle.ts';
20
+ export * from './context-usage-breakdown.ts';
20
21
  export * from './conversation-history-projector.ts';
21
22
  export * from './runtime-usage-accounting.ts';
package/dist/index.js CHANGED
@@ -17,5 +17,6 @@ export * from "./context-projection.js";
17
17
  export * from "./context-projection-lifecycle.js";
18
18
  export * from "./context-accounting-pipeline.js";
19
19
  export * from "./context-accounting-lifecycle.js";
20
+ export * from "./context-usage-breakdown.js";
20
21
  export * from "./conversation-history-projector.js";
21
22
  export * from "./runtime-usage-accounting.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/runtime-core",
3
- "version": "0.0.5",
3
+ "version": "0.0.7",
4
4
  "description": "Host-neutral capability, permission, projection, and Evidence primitives for Peer Agent runtimes.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,7 +38,7 @@
38
38
  "LICENSE"
39
39
  ],
40
40
  "dependencies": {
41
- "@peer-agent/protocol": "0.0.5"
41
+ "@peer-agent/protocol": "0.0.7"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^5.9.3"