@peer-agent/protocol 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 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,25 @@
1
+ # @peer-agent/protocol
2
+
3
+ Host-neutral protocol contracts for Peer Agent runtimes, hosts, and clients.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @peer-agent/protocol
9
+ ```
10
+
11
+ `@peer-agent/protocol` contains the cross-host contract layer: runtime tool calls/results, capability manifests, grants, Evidence, Goal/task contracts, session/runtime snapshots, and related TypeScript types.
12
+
13
+ It does **not** execute local tools, access Electron, or install the `peer` CLI.
14
+
15
+ ## Who should use it
16
+
17
+ - custom Peer Agent hosts / adapters
18
+ - integrations that exchange runtime events or tool contracts
19
+ - TypeScript libraries that need stable host-neutral types
20
+
21
+ Most external hosts can install `@peer-agent/runtime-sdk`; it brings protocol transitively. Install protocol directly when you only need contracts/types.
22
+
23
+ ## Version policy
24
+
25
+ The public Open Runtime packages follow the repository root `VERSION` and the same release tag as Desktop / CLI during beta.
package/dist/chat.d.ts ADDED
@@ -0,0 +1,222 @@
1
+ import type { PendingDispatch, PendingHumanConfirmation, ResolvedHumanConfirmation, ThinkingProcess } from './execution.ts';
2
+ export type ConversationStatus = 'active' | 'inactive' | 'archived';
3
+ export interface ConversationMetadata {
4
+ readonly source?: string;
5
+ readonly [key: string]: unknown;
6
+ }
7
+ export interface Conversation {
8
+ readonly id: number;
9
+ readonly conversationUuid: string;
10
+ readonly title: string;
11
+ readonly agentId?: number;
12
+ readonly status: ConversationStatus;
13
+ readonly metadata?: ConversationMetadata;
14
+ readonly spectatorEnabled?: boolean;
15
+ readonly spectatorAclKey?: string | null;
16
+ readonly messageCount?: number;
17
+ readonly gmtCreate?: string;
18
+ readonly gmtModified?: string;
19
+ }
20
+ export type MessageRole = 'user' | 'assistant' | 'system' | 'tool';
21
+ export type MessageStatus = 'sending' | 'streaming' | 'done' | 'error';
22
+ export interface MessageReference {
23
+ readonly scopeId: string;
24
+ readonly label: string;
25
+ readonly text: string;
26
+ readonly metadata?: Record<string, unknown>;
27
+ }
28
+ export interface MessageImage {
29
+ readonly url: string;
30
+ readonly mimeType?: string;
31
+ readonly width?: number;
32
+ readonly height?: number;
33
+ }
34
+ export interface AssistantAction {
35
+ readonly id: string;
36
+ readonly label: string;
37
+ readonly style?: 'primary' | 'default' | 'danger';
38
+ readonly skillId: string;
39
+ readonly payload: {
40
+ readonly type: string;
41
+ readonly data?: unknown;
42
+ readonly messageUuid?: string;
43
+ };
44
+ }
45
+ export interface ChatMessage {
46
+ readonly id: string;
47
+ readonly role: MessageRole;
48
+ readonly content: string;
49
+ readonly timestamp: number;
50
+ readonly status?: MessageStatus;
51
+ readonly messageUuid?: string;
52
+ readonly rawMessageId?: number;
53
+ readonly images?: readonly MessageImage[];
54
+ readonly references?: readonly MessageReference[];
55
+ readonly actions?: readonly AssistantAction[];
56
+ readonly skillId?: string | number;
57
+ readonly skillName?: string;
58
+ readonly aiData?: unknown;
59
+ readonly renderData?: unknown;
60
+ readonly thinkingProcess?: ThinkingProcess;
61
+ readonly pendingDispatch?: PendingDispatch;
62
+ readonly pendingHumanConfirmation?: PendingHumanConfirmation;
63
+ readonly resolvedHumanConfirmation?: ResolvedHumanConfirmation;
64
+ readonly humanConfirmationHistory?: readonly ResolvedHumanConfirmation[];
65
+ readonly sender?: {
66
+ readonly id: number;
67
+ readonly name: string;
68
+ readonly type: 'siliconEmployee' | 'agent';
69
+ readonly depth: number;
70
+ readonly orgRole?: string;
71
+ };
72
+ }
73
+ export type MessageSource = {
74
+ readonly kind: 'live';
75
+ readonly conversationId: number;
76
+ } | {
77
+ readonly kind: 'frozen';
78
+ readonly shareUuid: string;
79
+ } | {
80
+ readonly kind: 'hybrid';
81
+ readonly conversationId: number;
82
+ readonly shareUuid: string;
83
+ };
84
+ export interface ConversationCapabilities {
85
+ readonly canSend: boolean;
86
+ readonly canEdit: boolean;
87
+ readonly canBranch: boolean;
88
+ readonly canShare: boolean;
89
+ }
90
+ export type ConversationLineage = {
91
+ readonly kind: 'sharedFrom';
92
+ readonly shareUuid: string;
93
+ readonly ownerWorkId: string;
94
+ readonly title: string;
95
+ readonly snapshotMessageCount: number;
96
+ readonly continuePolicy: 'disabled' | 'fork_only';
97
+ readonly derivationCount?: number;
98
+ } | {
99
+ readonly kind: 'derivedFrom';
100
+ readonly shareUuid: string;
101
+ readonly ownerWorkId: string;
102
+ readonly title: string;
103
+ readonly snapshotMessageCount: number;
104
+ } | null;
105
+ export interface ConversationView {
106
+ readonly source: MessageSource;
107
+ readonly capabilities: ConversationCapabilities;
108
+ readonly lineage: ConversationLineage;
109
+ readonly readOnly: boolean;
110
+ }
111
+ export type MessageNodeOrigin = 'live' | 'frozen';
112
+ export interface MessageActions {
113
+ readonly copy: boolean;
114
+ readonly regenerate: boolean;
115
+ readonly delete: boolean;
116
+ readonly branch: boolean;
117
+ readonly snapshot: boolean;
118
+ }
119
+ export interface ChatRuntimeState {
120
+ readonly conversation: Conversation | null;
121
+ readonly view: ConversationView | null;
122
+ readonly messages: readonly ChatMessage[];
123
+ readonly isStreaming: boolean;
124
+ readonly currentAssistantMessageId?: string;
125
+ readonly currentExecutionUuid?: string;
126
+ /**
127
+ * 当前用户消息触发的 run 标识(= userMessageUuid),由后端 `run_started`
128
+ * SSE 事件设置。main 进程在原 SSE 流断后用它作为重订阅
129
+ * `/api/chat/agent-runs/:runId/stream` 的寻址 key,跨多轮 pause-resume 持久。
130
+ */
131
+ readonly currentRunId?: string;
132
+ readonly pendingConfirmations: readonly PendingHumanConfirmation[];
133
+ readonly lastEventAt?: string;
134
+ readonly error?: string;
135
+ }
136
+ export interface ChatStreamEvent {
137
+ readonly event: string;
138
+ readonly data: unknown;
139
+ readonly id?: string;
140
+ readonly retry?: number;
141
+ }
142
+ export interface ConversationListData {
143
+ readonly list: readonly Conversation[];
144
+ readonly total: number;
145
+ readonly limit?: number;
146
+ readonly offset?: number;
147
+ }
148
+ export interface MessageListData {
149
+ readonly list: readonly ChatMessage[];
150
+ readonly total: number;
151
+ readonly limit?: number;
152
+ readonly offset?: number;
153
+ readonly hasMore?: boolean;
154
+ }
155
+ export interface ChatStreamStartResult {
156
+ readonly streamId: string;
157
+ }
158
+ export interface ChatStreamEventEnvelope {
159
+ readonly streamId: string;
160
+ readonly event: ChatStreamEvent;
161
+ readonly receivedAt: string;
162
+ }
163
+ export interface ChatStreamDoneEnvelope {
164
+ readonly streamId: string;
165
+ readonly completedAt: string;
166
+ }
167
+ export interface ChatStreamErrorEnvelope {
168
+ readonly streamId: string;
169
+ readonly error: string;
170
+ readonly failedAt: string;
171
+ }
172
+ export interface ConversationMutationResult {
173
+ readonly ok?: boolean;
174
+ readonly code?: string;
175
+ readonly message?: string;
176
+ }
177
+ export interface BranchConversationResult {
178
+ readonly conversation: Conversation;
179
+ readonly messages?: readonly ChatMessage[];
180
+ }
181
+ export interface ThinkingDetailData {
182
+ readonly conversationId?: number;
183
+ readonly messageId?: number;
184
+ readonly messageUuid?: string;
185
+ readonly thinkingProcess?: ThinkingProcess;
186
+ readonly events?: readonly ChatStreamEvent[];
187
+ }
188
+ export interface AgentSummary {
189
+ readonly id: number | string;
190
+ readonly name: string;
191
+ readonly description?: string;
192
+ readonly avatar?: string;
193
+ readonly status?: string;
194
+ readonly metadata?: Record<string, unknown>;
195
+ }
196
+ export interface AgentListData {
197
+ readonly list: readonly AgentSummary[];
198
+ readonly total?: number;
199
+ }
200
+ export interface AssistantSuggestion {
201
+ readonly id: string;
202
+ readonly label: string;
203
+ readonly prompt: string;
204
+ readonly description?: string;
205
+ readonly source?: string;
206
+ }
207
+ export interface AssistantSuggestionListData {
208
+ readonly list: readonly AssistantSuggestion[];
209
+ }
210
+ export interface InlineCompletionData {
211
+ readonly text: string;
212
+ readonly source?: string;
213
+ }
214
+ export declare const FULL_CONVERSATION_CAPABILITIES: ConversationCapabilities;
215
+ export declare const READ_ONLY_CONVERSATION_CAPABILITIES: ConversationCapabilities;
216
+ export declare const STRICT_SPECTATOR_CONVERSATION_CAPABILITIES: ConversationCapabilities;
217
+ export declare function isReadOnlyConversation(capabilities: ConversationCapabilities): boolean;
218
+ export declare function buildConversationView(params: {
219
+ readonly source: MessageSource;
220
+ readonly capabilities: ConversationCapabilities;
221
+ readonly lineage?: ConversationLineage;
222
+ }): ConversationView;
package/dist/chat.js ADDED
@@ -0,0 +1,29 @@
1
+ export const FULL_CONVERSATION_CAPABILITIES = {
2
+ canSend: true,
3
+ canEdit: true,
4
+ canBranch: true,
5
+ canShare: true,
6
+ };
7
+ export const READ_ONLY_CONVERSATION_CAPABILITIES = {
8
+ canSend: false,
9
+ canEdit: false,
10
+ canBranch: true,
11
+ canShare: false,
12
+ };
13
+ export const STRICT_SPECTATOR_CONVERSATION_CAPABILITIES = {
14
+ canSend: false,
15
+ canEdit: false,
16
+ canBranch: false,
17
+ canShare: false,
18
+ };
19
+ export function isReadOnlyConversation(capabilities) {
20
+ return !capabilities.canSend && !capabilities.canEdit && !capabilities.canShare;
21
+ }
22
+ export function buildConversationView(params) {
23
+ return {
24
+ source: params.source,
25
+ capabilities: params.capabilities,
26
+ lineage: params.lineage ?? null,
27
+ readOnly: isReadOnlyConversation(params.capabilities),
28
+ };
29
+ }
@@ -0,0 +1,37 @@
1
+ /** 压缩摘要的产生方式,与 runtime-core CompactionMethod 保持同枚举。 */
2
+ export type CompactionMarkerMethod = 'llm' | 'structured' | 'structural' | 'fallback_drop';
3
+ /** 持久化在 handoff 消息 `_compaction` 字段上的共享 marker 形状。 */
4
+ export interface ConversationCompactionMarker {
5
+ readonly method: CompactionMarkerMethod;
6
+ /** LLM 摘要失败降级原因(仅降级时存在)。 */
7
+ readonly fallbackReason?: string;
8
+ readonly fallbackDetail?: string;
9
+ /** 本 marker 所代表的被压缩消息总数(含之前 marker 累计代表的数量)。 */
10
+ readonly originalMessageCount: number;
11
+ /** 之前 marker 已代表的消息数(连续性 carry-forward)。 */
12
+ readonly previousMessageCount: number;
13
+ /** 本次新压缩的消息数。 */
14
+ readonly deltaMessageCount: number;
15
+ readonly beforeTokens: number;
16
+ readonly afterTokens: number;
17
+ /** 累计连续性摘要(carry-forward 后),恢复端经 continuity 通道注入 system context。 */
18
+ readonly summary: string;
19
+ /** 近期关键决策锚点(可为空数组)。 */
20
+ readonly decisionAnchors: readonly string[];
21
+ }
22
+ /**
23
+ * 两端唯一的 `_compaction` marker 构造器。
24
+ * 数值一律钳制为非负整数;method 非法时回退 'structured';可选降级字段仅在非空时出现。
25
+ */
26
+ export declare function buildCompactionMarker(input: {
27
+ readonly method?: unknown;
28
+ readonly fallbackReason?: string | null;
29
+ readonly fallbackDetail?: string | null;
30
+ readonly originalMessageCount?: number | null;
31
+ readonly previousMessageCount?: number | null;
32
+ readonly deltaMessageCount?: number | null;
33
+ readonly beforeTokens?: number | null;
34
+ readonly afterTokens?: number | null;
35
+ readonly summary?: string | null;
36
+ readonly decisionAnchors?: readonly string[] | null;
37
+ }): ConversationCompactionMarker;
@@ -0,0 +1,40 @@
1
+ // 跨宿主压缩恢复形状契约(23 号治理文档不变式 3)。
2
+ //
3
+ // `_compaction` marker 是 Desktop 与 CLI/TUI 共享会话事实面的一部分:
4
+ // 任一端压缩后,另一端必须能按同一形状恢复 active provider history 分界与连续性摘要。
5
+ // 两端持久化必须经 buildCompactionMarker() 产出,不得手写字面量,防止字段漂移。
6
+ function nonNegativeInt(value) {
7
+ const parsed = Number(value);
8
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;
9
+ }
10
+ function normalizeMethod(value) {
11
+ return value === 'llm' || value === 'structured' || value === 'structural' || value === 'fallback_drop'
12
+ ? value
13
+ : 'structured';
14
+ }
15
+ /**
16
+ * 两端唯一的 `_compaction` marker 构造器。
17
+ * 数值一律钳制为非负整数;method 非法时回退 'structured';可选降级字段仅在非空时出现。
18
+ */
19
+ export function buildCompactionMarker(input) {
20
+ const fallbackReason = typeof input.fallbackReason === 'string' && input.fallbackReason.trim()
21
+ ? input.fallbackReason
22
+ : undefined;
23
+ const fallbackDetail = typeof input.fallbackDetail === 'string' && input.fallbackDetail.trim()
24
+ ? input.fallbackDetail
25
+ : undefined;
26
+ return {
27
+ method: normalizeMethod(input.method),
28
+ ...(fallbackReason ? { fallbackReason } : {}),
29
+ ...(fallbackDetail ? { fallbackDetail } : {}),
30
+ originalMessageCount: nonNegativeInt(input.originalMessageCount),
31
+ previousMessageCount: nonNegativeInt(input.previousMessageCount),
32
+ deltaMessageCount: nonNegativeInt(input.deltaMessageCount),
33
+ beforeTokens: nonNegativeInt(input.beforeTokens),
34
+ afterTokens: nonNegativeInt(input.afterTokens),
35
+ summary: typeof input.summary === 'string' ? input.summary : '',
36
+ decisionAnchors: Array.isArray(input.decisionAnchors)
37
+ ? input.decisionAnchors.filter((anchor) => typeof anchor === 'string' && anchor.length > 0)
38
+ : [],
39
+ };
40
+ }
@@ -0,0 +1,84 @@
1
+ export type ContextCountCapability = {
2
+ readonly kind: 'provider_count_api';
3
+ } | {
4
+ readonly kind: 'provider_tokenizer';
5
+ readonly tokenizerVersion: string;
6
+ } | {
7
+ readonly kind: 'observed_usage_only';
8
+ } | {
9
+ readonly kind: 'unavailable';
10
+ };
11
+ export type ContextAccountingPhase = 'request_preflight' | 'stream_preview' | 'tool_result' | 'post_compaction' | 'turn_complete' | 'restored' | 'model_changed';
12
+ export type ContextAccountingPressureSource = 'provider_usage' | 'provider_count_api' | 'provider_tokenizer' | 'provider_error_evidence' | 'unknown';
13
+ /**
14
+ * Canonical cross-host model identity used by context accounting.
15
+ *
16
+ * Desktop persists a credential/provider id and model separately. Older TUI
17
+ * builds persisted `${providerId}::${modelId}` in the provider-id field. This
18
+ * normalizer makes both shapes converge without treating a host migration as a
19
+ * model change.
20
+ */
21
+ export declare function contextAccountingModelKey(providerId: string | null | undefined, modelId: string | null | undefined): string;
22
+ export interface ContextAccountingObserved {
23
+ readonly inputTokens: number;
24
+ readonly requestFingerprint: string;
25
+ readonly compactionEpoch: number;
26
+ readonly source: 'provider_usage';
27
+ readonly observedAt: number;
28
+ readonly supersededByCompactionRevision?: number;
29
+ }
30
+ export interface ContextAccountingCounted {
31
+ readonly inputTokens: number;
32
+ readonly requestFingerprint: string;
33
+ readonly compactionEpoch: number;
34
+ readonly source: 'provider_count_api' | 'provider_tokenizer';
35
+ readonly countedAt: number;
36
+ }
37
+ export interface ContextOverflowEvidence {
38
+ readonly requestedTokens?: number;
39
+ readonly maximumTokens?: number;
40
+ readonly status?: number;
41
+ readonly message: string;
42
+ }
43
+ export interface ContextCountVerification {
44
+ readonly requestFingerprint: string;
45
+ readonly countedInputTokens: number;
46
+ readonly observedInputTokens: number;
47
+ readonly absoluteDelta: number;
48
+ readonly relativeDelta: number;
49
+ readonly tolerance: number;
50
+ readonly status: 'verified' | 'drift';
51
+ readonly verifiedAt: number;
52
+ }
53
+ /**
54
+ * The only cross-host context-capacity state.
55
+ *
56
+ * Numeric occupancy is present only when it is backed by provider usage,
57
+ * provider-aligned exact count, or provider overflow evidence. Pending draft,
58
+ * stream, and tool changes are represented as pending state and character
59
+ * counts; they never become a fabricated token percentage.
60
+ */
61
+ export interface ContextAccountingSnapshot {
62
+ readonly version: 1;
63
+ readonly conversationId: string;
64
+ readonly contentRevision: number;
65
+ readonly modelKey: string;
66
+ readonly revision: number;
67
+ readonly phase: ContextAccountingPhase;
68
+ readonly compactionEpoch: number;
69
+ readonly contextWindow: number | null;
70
+ readonly inputBudget: number | null;
71
+ readonly compactionThresholdTokens: number | null;
72
+ readonly authoritativeInputTokens: number | null;
73
+ readonly percent: number | null;
74
+ readonly pressureSource: ContextAccountingPressureSource;
75
+ readonly pendingUncountedChanges: boolean;
76
+ readonly pendingContentChars: number;
77
+ readonly countCapability: ContextCountCapability;
78
+ readonly counterStatus: 'active' | 'degraded';
79
+ readonly updatedAt: number;
80
+ readonly lastObserved?: ContextAccountingObserved;
81
+ readonly nextCounted?: ContextAccountingCounted;
82
+ readonly lastOverflow?: ContextOverflowEvidence;
83
+ readonly verification?: ContextCountVerification;
84
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Canonical cross-host model identity used by context accounting.
3
+ *
4
+ * Desktop persists a credential/provider id and model separately. Older TUI
5
+ * builds persisted `${providerId}::${modelId}` in the provider-id field. This
6
+ * normalizer makes both shapes converge without treating a host migration as a
7
+ * model change.
8
+ */
9
+ export function contextAccountingModelKey(providerId, modelId) {
10
+ const provider = typeof providerId === 'string' && providerId.trim()
11
+ ? providerId.trim()
12
+ : 'unknown-provider';
13
+ const model = typeof modelId === 'string' && modelId.trim()
14
+ ? modelId.trim()
15
+ : '';
16
+ const separator = provider.lastIndexOf('::');
17
+ const baseProvider = separator > 0 ? provider.slice(0, separator) : provider;
18
+ const embeddedModel = separator > 0 ? provider.slice(separator + 2) : '';
19
+ const resolvedModel = model || embeddedModel;
20
+ return resolvedModel ? `${baseProvider}::${resolvedModel}` : baseProvider;
21
+ }