@peer-agent/protocol 0.1.0-rc.41 → 0.1.0-rc.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.
@@ -4,10 +4,13 @@ export declare function isModelReasoningEffort(value: unknown): value is ModelRe
4
4
  export declare function modelReasoningLevels(provider: {
5
5
  readonly supportsReasoning?: unknown;
6
6
  readonly reasoningEffortLevels?: unknown;
7
+ readonly reasoningEffortMap?: unknown;
7
8
  }): readonly ModelReasoningEffort[];
8
9
  export declare function modelDefaultReasoningEffort(provider: {
9
10
  readonly supportsReasoning?: unknown;
10
11
  readonly reasoningEffortLevels?: unknown;
12
+ readonly reasoningEffortMap?: unknown;
11
13
  readonly reasoningEffort?: unknown;
14
+ readonly reasoningDefaultEffort?: unknown;
12
15
  readonly defaultEffort?: unknown;
13
16
  }): ModelReasoningEffort | undefined;
@@ -3,14 +3,21 @@ export function isModelReasoningEffort(value) {
3
3
  return ORDER.includes(value);
4
4
  }
5
5
  export function modelReasoningLevels(provider) {
6
- if (provider.supportsReasoning === false || !Array.isArray(provider.reasoningEffortLevels))
6
+ if (provider.supportsReasoning === false)
7
7
  return [];
8
- const declared = provider.reasoningEffortLevels;
9
- return ORDER.filter(value => declared.includes(value));
8
+ if (Array.isArray(provider.reasoningEffortLevels)) {
9
+ const declared = provider.reasoningEffortLevels;
10
+ return ORDER.filter(value => declared.includes(value));
11
+ }
12
+ if (provider.reasoningEffortMap && typeof provider.reasoningEffortMap === 'object' && !Array.isArray(provider.reasoningEffortMap)) {
13
+ const keys = Object.keys(provider.reasoningEffortMap);
14
+ return ORDER.filter(value => keys.includes(value));
15
+ }
16
+ return [];
10
17
  }
11
18
  export function modelDefaultReasoningEffort(provider) {
12
19
  const levels = modelReasoningLevels(provider);
13
- for (const value of [provider.reasoningEffort, provider.defaultEffort, 'default', 'medium', 'high', 'low', ...levels]) {
20
+ for (const value of [provider.reasoningEffort, provider.reasoningDefaultEffort, provider.defaultEffort, 'default', 'medium', 'high', 'low', ...levels]) {
14
21
  if (isModelReasoningEffort(value) && levels.includes(value))
15
22
  return value;
16
23
  }
@@ -111,7 +111,9 @@ export declare function projectModelRoutingMenuOption(provider: {
111
111
  readonly enabled?: unknown;
112
112
  readonly supportsReasoning?: unknown;
113
113
  readonly reasoningEffortLevels?: unknown;
114
+ readonly reasoningEffortMap?: unknown;
114
115
  readonly reasoningEffort?: unknown;
116
+ readonly reasoningDefaultEffort?: unknown;
115
117
  readonly defaultEffort?: unknown;
116
118
  } | null | undefined): ModelRoutingMenuOption | null;
117
119
  export interface CatalogModel {
@@ -0,0 +1,21 @@
1
+ import type { SessionControlOperation } from './session-control.ts';
2
+ import { type SessionExecutionIdentity } from './session-control.ts';
3
+ type Recorder = NonNullable<SessionControlOperation['recorder']>;
4
+ export interface NativeOwnedProcess {
5
+ readonly schemaVersion: 1;
6
+ readonly kind: 'command';
7
+ readonly handleId: string;
8
+ readonly toolCallId: string;
9
+ readonly dispatchId: string;
10
+ readonly execution: SessionExecutionIdentity;
11
+ readonly generation: number;
12
+ readonly state: 'not_started' | 'starting' | 'running' | 'ended';
13
+ readonly owner: Recorder;
14
+ readonly child?: Recorder | null;
15
+ readonly stopObservation?: 'owned_completion' | 'owner_dead_not_started' | 'owner_dead_group_absent' | null;
16
+ }
17
+ /** Envelope shape only. Execution identity is validated by each owning contract. */
18
+ export declare function nativeProcessEnvelopeValid(raw: unknown): boolean;
19
+ /** Shape only: no value here proves local execution or process death. */
20
+ export declare function nativeProcessesInWork(work: unknown): readonly NativeOwnedProcess[];
21
+ export {};
@@ -0,0 +1,51 @@
1
+ import { normalizeSessionExecutionIdentity } from "./session-control.js";
2
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) ? v : {};
3
+ const text = (v, bytes) => typeof v === 'string' && v.length > 0 && v.length <= bytes && new TextEncoder().encode(v).length <= bytes;
4
+ const recorder = (v) => {
5
+ const r = object(v);
6
+ return Number.isInteger(r.pid) && r.pid > 0 && r.pid <= 2147483647
7
+ && ['bootId', 'pidStart', 'hostId', 'acquiredAt'].every(k => text(r[k], 8192));
8
+ };
9
+ /** Envelope shape only. Execution identity is validated by each owning contract. */
10
+ export function nativeProcessEnvelopeValid(raw) {
11
+ const p = object(raw), owner = object(p.owner), child = object(p.child);
12
+ const keys = ['schemaVersion', 'kind', 'handleId', 'toolCallId', 'dispatchId', 'execution', 'generation', 'state', 'owner', 'child', 'stopObservation'];
13
+ const validChild = p.child == null || recorder(child) && ['hostId', 'acquiredAt', 'bootId'].every(k => child[k] === owner[k]);
14
+ const gen = Number.isInteger(p.generation) && p.generation >= 0 && p.generation <= 64;
15
+ const phase = p.state === 'not_started' ? p.generation === 0 && p.child == null && p.stopObservation == null
16
+ : p.state === 'starting' ? p.generation > 0 && p.child == null && p.stopObservation == null
17
+ : p.state === 'running' ? p.generation > 0 && p.child != null && p.stopObservation == null
18
+ : p.state === 'ended' && (p.stopObservation === 'owned_completion'
19
+ || p.stopObservation === 'owner_dead_not_started' && p.generation === 0 && p.child == null
20
+ || p.stopObservation === 'owner_dead_group_absent' && p.generation > 0 && p.child != null);
21
+ return p.schemaVersion === 1 && p.kind === 'command' && !Object.keys(p).some(k => !keys.includes(k))
22
+ && ['handleId', 'toolCallId', 'dispatchId'].every(k => text(p[k], 200))
23
+ && !!gen && !!phase && recorder(owner) && !!validChild;
24
+ }
25
+ /** Shape only: no value here proves local execution or process death. */
26
+ export function nativeProcessesInWork(work) {
27
+ const budget = object(object(work).budget);
28
+ const rows = [...Object.values(object(budget.attempts)).flatMap(a => {
29
+ const pending = object(a).pendingTools;
30
+ return Array.isArray(pending) ? pending : [];
31
+ }), ...(Array.isArray(budget.uncertainDispatches) ? budget.uncertainDispatches : [])];
32
+ const result = [];
33
+ for (const raw of rows) {
34
+ const row = object(raw);
35
+ if (!Object.hasOwn(row, 'nativeProcess'))
36
+ continue;
37
+ const p = object(row.nativeProcess), owner = object(p.owner);
38
+ const original = object(object(row.nativeRecorder).recorder);
39
+ const execution = normalizeSessionExecutionIdentity(p.execution);
40
+ const recordedExecution = normalizeSessionExecutionIdentity(object(row.nativeRecorder).execution);
41
+ if (!nativeProcessEnvelopeValid(p) || !recorder(original) || !execution || !recordedExecution
42
+ || JSON.stringify(execution) !== JSON.stringify(recordedExecution)
43
+ || !['pid', 'pidStart', 'bootId', 'hostId', 'acquiredAt'].every(k => owner[k] === original[k])
44
+ || p.toolCallId !== row.toolCallId || p.dispatchId !== row.dispatchId || result.length >= 128
45
+ || result.some(old => old.handleId === p.handleId || old.toolCallId === p.toolCallId || old.dispatchId === p.dispatchId)) {
46
+ throw new Error('native_process_invalid');
47
+ }
48
+ result.push(structuredClone(p));
49
+ }
50
+ return result;
51
+ }
@@ -1,14 +1,21 @@
1
1
  import type { ResourceFeedback } from './resource-feedback.ts';
2
- import type { ProjectInputAttachment, ProjectAgentSubmitInputResult } from './delegation.ts';
2
+ import type { ProjectInputAttachment, ProjectAgentSubmitInputResult, WorkSessionStatus } from './delegation.ts';
3
3
  export type LocalInputSurface = 'desktop' | 'quick_chat' | 'tui';
4
4
  export interface InputDraftQuote {
5
5
  readonly messageId: string;
6
6
  readonly text: string;
7
7
  }
8
+ export interface InputDraftTaskRef {
9
+ readonly sessionId: string;
10
+ readonly title: string;
11
+ readonly status: WorkSessionStatus | string;
12
+ readonly anchorMessageId?: string;
13
+ }
8
14
  export interface InputDraftValue {
9
15
  readonly text: string;
10
16
  readonly quote: InputDraftQuote | null;
11
17
  readonly attachments: readonly ProjectInputAttachment[];
18
+ readonly taskRefs?: readonly InputDraftTaskRef[];
12
19
  readonly resourceFeedback?: readonly ResourceFeedback[];
13
20
  }
14
21
  /** User intent only. Presence here never means the input was received or executed. */
@@ -16,6 +23,7 @@ export interface UnconfirmedProjectInput {
16
23
  readonly inputId: string;
17
24
  readonly text: string;
18
25
  readonly quoteRefs: readonly string[];
26
+ readonly taskRefs?: readonly InputDraftTaskRef[];
19
27
  readonly answerTo?: string;
20
28
  readonly attachments: readonly ProjectInputAttachment[];
21
29
  readonly resourceFeedback?: readonly ResourceFeedback[];
package/dist/project.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import type { ProjectModelPolicy } from './model-routing.ts';
6
6
  import type { PendingApprovalState, WorkSessionStatus } from './delegation.ts';
7
+ import type { FollowUpProjection } from './task-overview.ts';
7
8
  export interface DiagnosticText {
8
9
  readonly length: number;
9
10
  readonly sha256: string;
@@ -133,11 +134,25 @@ export type ProjectHostTakeoverResult = {
133
134
  readonly ok: false;
134
135
  readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'HOST_UNAVAILABLE' | 'INVALID_INPUT';
135
136
  };
137
+ export declare const BOT_AVATAR_HEADS: readonly ["none", "beret", "glasses", "beanie", "vermeer", "straw", "headphones", "crown"];
138
+ export type BotAvatarHead = (typeof BOT_AVATAR_HEADS)[number];
139
+ export declare const BOT_AVATAR_NECKS: readonly ["bowtie", "scarf", "sweater", "moon", "sailor", "cape"];
140
+ export type BotAvatarNeck = (typeof BOT_AVATAR_NECKS)[number];
141
+ export interface BotAvatarPartsPatch {
142
+ readonly shape?: string;
143
+ readonly color?: string;
144
+ readonly head?: BotAvatarHead;
145
+ readonly neck?: BotAvatarNeck;
146
+ readonly backdrop?: boolean;
147
+ }
136
148
  export type BotAvatar = {
137
149
  readonly kind: 'generated';
138
150
  readonly shape: string;
139
151
  readonly color: string;
140
152
  readonly variant?: number;
153
+ readonly head?: BotAvatarHead;
154
+ readonly neck?: BotAvatarNeck;
155
+ readonly backdrop?: boolean;
141
156
  } | {
142
157
  readonly kind: 'image';
143
158
  readonly ref: string;
@@ -149,6 +164,19 @@ export type BotAvatarReadResult = {
149
164
  readonly ok: false;
150
165
  readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'INVALID_IMAGE';
151
166
  };
167
+ export type BotCommunicationStyle = 'natural' | 'concise' | 'detailed' | 'technical';
168
+ export type BotProfileCommunicationStyle = 'inherit' | BotCommunicationStyle;
169
+ /** Per-bot capability mounting overrides (inherits global enabled state when absent). */
170
+ export interface BotCapabilityPolicy {
171
+ /** Skill IDs explicitly mounted on this bot (overrides global disable). */
172
+ readonly enabledSkillIds?: readonly string[];
173
+ /** Skill IDs explicitly unmounted on this bot (overrides global/workspace enable). */
174
+ readonly disabledSkillIds?: readonly string[];
175
+ /** MCP server IDs explicitly mounted on this bot (overrides global disable). */
176
+ readonly enabledMcpIds?: readonly string[];
177
+ /** MCP server IDs explicitly unmounted on this bot (overrides global enable). */
178
+ readonly disabledMcpIds?: readonly string[];
179
+ }
152
180
  export interface BotProfile {
153
181
  readonly workspaceId: string;
154
182
  readonly displayName: string;
@@ -156,6 +184,7 @@ export interface BotProfile {
156
184
  readonly managed?: boolean;
157
185
  readonly agentConversationId?: string;
158
186
  readonly proactivity?: 'inherit' | 'quiet' | 'low' | 'standard' | 'high' | 'muted';
187
+ readonly communicationStyle?: BotProfileCommunicationStyle;
159
188
  /** Absent means this bot uses memory. */
160
189
  readonly memoryEnabled?: boolean;
161
190
  readonly planApproval?: 'never' | 'writes' | 'always';
@@ -177,6 +206,8 @@ export interface BotProfile {
177
206
  readonly removePending: boolean;
178
207
  } | null;
179
208
  readonly modelPolicy?: ProjectModelPolicy | null;
209
+ /** Bot-mounted Skills & MCP overrides inherited by all derived child tasks. */
210
+ readonly capabilityPolicy?: BotCapabilityPolicy | null;
180
211
  readonly updatedAt?: string;
181
212
  }
182
213
  export interface BotRowState {
@@ -193,6 +224,9 @@ export interface BotListItem {
193
224
  readonly preview: string;
194
225
  readonly lastActiveAt: string;
195
226
  readonly state: BotRowState;
227
+ readonly activeSessions?: readonly BotListSession[];
228
+ readonly activeSessionTotal?: number;
229
+ readonly historySessionTotal?: number;
196
230
  }
197
231
  export interface BotListFilter {
198
232
  readonly query?: string;
@@ -268,8 +302,18 @@ export type ProjectAgentStopResponseResult = {
268
302
  readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'HOST_OFFLINE' | 'STALE_TURN' | 'INVALID_INPUT';
269
303
  };
270
304
  export interface BotListSession {
305
+ readonly sessionId?: string;
306
+ readonly title?: string;
271
307
  readonly status: WorkSessionStatus;
272
308
  readonly updatedAt?: string;
309
+ readonly followUp?: FollowUpProjection;
310
+ readonly phaseLabel?: string;
311
+ readonly anchorMessageId?: string;
312
+ readonly planId?: string;
313
+ readonly conversationId?: string;
314
+ readonly queueReason?: string;
315
+ readonly resultConfirmationRequired?: boolean;
316
+ readonly completionReviewRequired?: boolean;
273
317
  }
274
318
  export interface BotListApproval {
275
319
  readonly state: PendingApprovalState;
@@ -298,3 +342,9 @@ export declare function projectBotListItem(input: {
298
342
  }): BotListItem;
299
343
  export declare function sortBotList(items: readonly BotListItem[]): BotListItem[];
300
344
  export declare function filterBotList(items: readonly BotListItem[], filter?: BotListFilter): BotListItem[];
345
+ export declare function normalizeBotCapabilityPolicy(policy: BotCapabilityPolicy | null | undefined): BotCapabilityPolicy | null;
346
+ export declare function hasBotCapabilityOverrides(policy: BotCapabilityPolicy | null | undefined): boolean;
347
+ export declare function resolveBotSkillEnabled(policy: BotCapabilityPolicy | null | undefined, skillId: string, defaultEnabled: boolean): boolean;
348
+ export declare function resolveBotMcpEnabled(policy: BotCapabilityPolicy | null | undefined, mcpId: string, defaultEnabled: boolean): boolean;
349
+ export declare function toggleBotSkillOverride(policy: BotCapabilityPolicy | null | undefined, skillId: string, defaultEnabled: boolean, nextEnabled: boolean): BotCapabilityPolicy | null;
350
+ export declare function toggleBotMcpOverride(policy: BotCapabilityPolicy | null | undefined, mcpId: string, defaultEnabled: boolean, nextEnabled: boolean): BotCapabilityPolicy | null;
package/dist/project.js CHANGED
@@ -2,6 +2,24 @@
2
2
  * Bot list projection. Sort is recent activity only.
3
3
  * needsYou changes the badge and the filter, not the order.
4
4
  */
5
+ export const BOT_AVATAR_HEADS = [
6
+ 'none',
7
+ 'beret',
8
+ 'glasses',
9
+ 'beanie',
10
+ 'vermeer',
11
+ 'straw',
12
+ 'headphones',
13
+ 'crown',
14
+ ];
15
+ export const BOT_AVATAR_NECKS = [
16
+ 'bowtie',
17
+ 'scarf',
18
+ 'sweater',
19
+ 'moon',
20
+ 'sailor',
21
+ 'cape',
22
+ ];
5
23
  /** Display contract version for persisted agent_turn records (ADR87 D4).
6
24
  * Version 2: public text carries role, the canonical agent_reply is the only
7
25
  * answer body, and the implicit pure-text fallback reply is closed. Absent
@@ -107,3 +125,98 @@ export function filterBotList(items, filter = {}) {
107
125
  return haystack.includes(query);
108
126
  });
109
127
  }
128
+ function dedupCapabilityIds(ids) {
129
+ if (!Array.isArray(ids))
130
+ return [];
131
+ const out = [];
132
+ const seen = new Set();
133
+ for (const raw of ids) {
134
+ if (typeof raw !== 'string')
135
+ continue;
136
+ const trimmed = raw.trim();
137
+ if (!trimmed || seen.has(trimmed))
138
+ continue;
139
+ seen.add(trimmed);
140
+ out.push(trimmed);
141
+ }
142
+ return out;
143
+ }
144
+ export function normalizeBotCapabilityPolicy(policy) {
145
+ if (!policy || typeof policy !== 'object')
146
+ return null;
147
+ const disabledSkillIds = dedupCapabilityIds(policy.disabledSkillIds);
148
+ const disabledSkillSet = new Set(disabledSkillIds);
149
+ const enabledSkillIds = dedupCapabilityIds(policy.enabledSkillIds).filter((id) => !disabledSkillSet.has(id));
150
+ const disabledMcpIds = dedupCapabilityIds(policy.disabledMcpIds);
151
+ const disabledMcpSet = new Set(disabledMcpIds);
152
+ const enabledMcpIds = dedupCapabilityIds(policy.enabledMcpIds).filter((id) => !disabledMcpSet.has(id));
153
+ if (enabledSkillIds.length === 0
154
+ && disabledSkillIds.length === 0
155
+ && enabledMcpIds.length === 0
156
+ && disabledMcpIds.length === 0) {
157
+ return null;
158
+ }
159
+ return {
160
+ ...(enabledSkillIds.length > 0 ? { enabledSkillIds } : {}),
161
+ ...(disabledSkillIds.length > 0 ? { disabledSkillIds } : {}),
162
+ ...(enabledMcpIds.length > 0 ? { enabledMcpIds } : {}),
163
+ ...(disabledMcpIds.length > 0 ? { disabledMcpIds } : {}),
164
+ };
165
+ }
166
+ export function hasBotCapabilityOverrides(policy) {
167
+ return normalizeBotCapabilityPolicy(policy) !== null;
168
+ }
169
+ export function resolveBotSkillEnabled(policy, skillId, defaultEnabled) {
170
+ if (!policy)
171
+ return defaultEnabled;
172
+ if (policy.disabledSkillIds?.includes(skillId))
173
+ return false;
174
+ if (policy.enabledSkillIds?.includes(skillId))
175
+ return true;
176
+ return defaultEnabled;
177
+ }
178
+ export function resolveBotMcpEnabled(policy, mcpId, defaultEnabled) {
179
+ if (!policy)
180
+ return defaultEnabled;
181
+ if (policy.disabledMcpIds?.includes(mcpId))
182
+ return false;
183
+ if (policy.enabledMcpIds?.includes(mcpId))
184
+ return true;
185
+ return defaultEnabled;
186
+ }
187
+ export function toggleBotSkillOverride(policy, skillId, defaultEnabled, nextEnabled) {
188
+ const id = skillId.trim();
189
+ if (!id)
190
+ return normalizeBotCapabilityPolicy(policy);
191
+ const enabledSkillIds = dedupCapabilityIds(policy?.enabledSkillIds).filter((item) => item !== id);
192
+ const disabledSkillIds = dedupCapabilityIds(policy?.disabledSkillIds).filter((item) => item !== id);
193
+ if (nextEnabled !== defaultEnabled) {
194
+ if (nextEnabled)
195
+ enabledSkillIds.push(id);
196
+ else
197
+ disabledSkillIds.push(id);
198
+ }
199
+ return normalizeBotCapabilityPolicy({
200
+ ...policy,
201
+ enabledSkillIds,
202
+ disabledSkillIds,
203
+ });
204
+ }
205
+ export function toggleBotMcpOverride(policy, mcpId, defaultEnabled, nextEnabled) {
206
+ const id = mcpId.trim();
207
+ if (!id)
208
+ return normalizeBotCapabilityPolicy(policy);
209
+ const enabledMcpIds = dedupCapabilityIds(policy?.enabledMcpIds).filter((item) => item !== id);
210
+ const disabledMcpIds = dedupCapabilityIds(policy?.disabledMcpIds).filter((item) => item !== id);
211
+ if (nextEnabled !== defaultEnabled) {
212
+ if (nextEnabled)
213
+ enabledMcpIds.push(id);
214
+ else
215
+ disabledMcpIds.push(id);
216
+ }
217
+ return normalizeBotCapabilityPolicy({
218
+ ...policy,
219
+ enabledMcpIds,
220
+ disabledMcpIds,
221
+ });
222
+ }
@@ -7,7 +7,7 @@ const ownerships = new Set(['live', 'ended', 'unknown']);
7
7
  const owners = new Set(['bot', 'user', 'none']);
8
8
  const reasons = new Set(['settled', 'superseded', 'stop_confirmed', 'user_withdrawn',
9
9
  'stop_unconfirmed', 'human_request', 'awaiting_human_gate', 'technical_block', 'local_persistence_failed', 'awaiting_acceptance_technical',
10
- 'verification_failed', 'live_execution', 'paused', 'unknown_facts', 'obligation_indexed']);
10
+ 'verification_failed', 'execution_failed', 'live_execution', 'paused', 'unknown_facts', 'obligation_indexed']);
11
11
  const hostReasons = new Set(['live_execution', 'stop_unconfirmed', 'unknown_facts', 'local_persistence_failed']);
12
12
  export function runtimeSessionFacts(value) {
13
13
  const row = record(value), origin = record(row.origin), cancellation = record(origin.cancellation);
@@ -36,7 +36,9 @@ export function runtimeSessionFacts(value) {
36
36
  : executionOwnership === 'live' || stopping || owner === 'bot' && hostReasons.has(reason) ? 'host'
37
37
  : owner === 'none' ? 'none' : 'model';
38
38
  return { sessionId, status, valid, executionOwnership, owner, reason, handling,
39
- pendingManaged: reason === 'obligation_indexed' ? false : handling === 'host' || handling === 'user' || !['accepted', 'cancelled'].includes(status) };
39
+ pendingManaged: reason === 'obligation_indexed' || (reason === 'execution_failed' && handling === 'none')
40
+ ? false
41
+ : handling === 'host' || handling === 'user' || !['accepted', 'cancelled'].includes(status) };
40
42
  }
41
43
  /** Missing/invalid facts remain obligations; a valid public terminal does not invent live ownership. */
42
44
  export function hasPendingRuntimeSessions(sessions, expectedIds = []) {
@@ -163,6 +163,17 @@ export interface UnknownOutcomeResolution {
163
163
  readonly unknownCalls: readonly string[];
164
164
  readonly at: string;
165
165
  }
166
+ /** ADR 131: local transport ownership only; never proof of remote tool effects. */
167
+ export interface NativeMcpHandleObservation {
168
+ readonly schemaVersion: 1;
169
+ readonly role: 'rpc' | 'connection';
170
+ readonly transport: 'stdio' | 'streamable_http' | 'sse';
171
+ readonly registryRevision: string;
172
+ readonly ownerRecorder: NonNullable<SessionControlOperation['recorder']>;
173
+ readonly childRecorder?: NonNullable<SessionControlOperation['recorder']>;
174
+ readonly ownerStopObservation?: 'original_owner_dead';
175
+ readonly childStopObservation?: 'group_absent';
176
+ }
166
177
  export interface ExecutionResourceClaim {
167
178
  readonly claimId: string;
168
179
  readonly resourceRef: string;
@@ -176,6 +187,7 @@ export interface ExecutionResourceClaim {
176
187
  readonly toolCallId: string;
177
188
  readonly state: 'active' | 'ended' | 'unknown';
178
189
  readonly completedAt?: string;
190
+ readonly nativeMcp?: NativeMcpHandleObservation;
179
191
  }>>;
180
192
  readonly evidenceCalls: readonly string[];
181
193
  /** Absent means the legacy directory scope derived from resourceRef; dispatch-declared scopes arrive with claim scope convergence. */
@@ -407,6 +407,7 @@ export interface LifecycleFacts {
407
407
  readonly interrupted?: boolean;
408
408
  readonly interruptionOrigin?: import('./agent-supervision.ts').InterruptionOrigin;
409
409
  readonly verificationActive?: boolean;
410
+ readonly verificationFailed?: boolean;
410
411
  readonly blockedReason?: string;
411
412
  readonly cancellationPhase?: string;
412
413
  readonly cancellationDisposition?: 'user_withdrawn';
@@ -427,7 +428,7 @@ export interface LifecycleCoreDecision extends ProjectionDecision {
427
428
  * `inCurrentList` 是派生事实,不允许消费端各自按 status 再判一次。
428
429
  */
429
430
  export type FollowUpOwner = 'bot' | 'user' | 'none';
430
- export type FollowUpReason = 'settled' | 'superseded' | 'stop_confirmed' | 'user_withdrawn' | 'stop_unconfirmed' | 'human_request' | 'awaiting_human_gate' | 'technical_block' | 'local_persistence_failed' | 'awaiting_acceptance_technical' | 'verification_failed' | 'live_execution' | 'paused' | 'unknown_facts' | 'obligation_indexed';
431
+ export type FollowUpReason = 'settled' | 'superseded' | 'stop_confirmed' | 'user_withdrawn' | 'stop_unconfirmed' | 'human_request' | 'awaiting_human_gate' | 'technical_block' | 'local_persistence_failed' | 'awaiting_acceptance_technical' | 'verification_failed' | 'execution_failed' | 'live_execution' | 'paused' | 'unknown_facts' | 'obligation_indexed';
431
432
  export interface FollowUpProjection {
432
433
  readonly owner: FollowUpOwner;
433
434
  readonly inCurrentList: boolean;
@@ -39,8 +39,11 @@ export function decideFollowUp(decision, facts = {}, ownership = 'unknown') {
39
39
  // 3) 核验失败/缺证据:即使存在历史 accepted 事实也不能静默(那次验收是旧结论)。
40
40
  if (['failed', 'waiting_agent'].includes(status) && facts.blockedReason === 'conversation_persistence_failed')
41
41
  return followUpOf('bot', 'local_persistence_failed');
42
- if (status === 'failed')
42
+ if (status === 'result_ready' && facts.verificationFailed === true)
43
43
  return followUpOf('bot', 'verification_failed');
44
+ // 终态执行失败(未产生可核验结果):归入历史记录,不再伪装成待重验任务钉死在活跃列表。
45
+ if (status === 'failed')
46
+ return followUpOf('none', 'execution_failed');
44
47
  if (facts.accepted === true)
45
48
  return followUpOf('none', 'settled');
46
49
  if (stopStatus)
@@ -2,6 +2,7 @@
2
2
  * Usage scopes are deliberately explicit because the same token fields have
3
3
  * different meanings at each runtime boundary.
4
4
  */
5
+ import type { SessionExecutionIdentity } from './session-control.ts';
5
6
  export type UsageScope = 'provider_request' | 'runtime_turn' | 'conversation_lifetime';
6
7
  export interface UsageAmounts {
7
8
  readonly inputTokens: number;
@@ -22,6 +23,34 @@ export interface RuntimeTurnUsage extends UsageAmounts {
22
23
  readonly usageScope: 'runtime_turn';
23
24
  readonly providerRequestCount: number;
24
25
  }
26
+ /** ADR131 canonical billing snapshot. It never seeds context or proves execution. */
27
+ export interface NativeRuntimeUsageSnapshot {
28
+ readonly schemaVersion: 1;
29
+ readonly knownAmountsOnly: true;
30
+ readonly workId: string;
31
+ readonly execution: SessionExecutionIdentity;
32
+ readonly conversationId: string;
33
+ readonly usage: RuntimeTurnUsage;
34
+ readonly attribution: {
35
+ readonly id: string;
36
+ readonly streamId: string;
37
+ readonly at: string;
38
+ readonly modelProviderId: string;
39
+ readonly model: string;
40
+ readonly groupId?: string | null;
41
+ readonly role: 'work_session';
42
+ readonly workspaceId: string;
43
+ readonly providerName?: string | null;
44
+ readonly estimatedCostUsd?: number | null;
45
+ readonly pricingSource?: string | null;
46
+ };
47
+ }
48
+ /** One bounded native recovery batch; remaining records retain their identity. */
49
+ export interface NativeUsageRecoveryProgress {
50
+ readonly schemaVersion: 1;
51
+ readonly settled: number;
52
+ readonly remaining: number;
53
+ }
25
54
  /** Durable billable sum for one provider/model key inside a conversation ledger. */
26
55
  export interface ConversationLifetimeModelUsage {
27
56
  /** Stable provider binding id, e.g. '5198c365-...::ultimate'. */
@@ -1,4 +1,13 @@
1
1
  import type { ProjectRecoveryFailureKind } from './project-agent-failure.ts';
2
+ import type { SessionExecutionIdentity, SessionControlOperation } from './session-control.ts';
3
+ import type { NativeOwnedProcess } from './native-process.ts';
4
+ /** ADR 131 native attempt metadata. Shape alone proves neither death nor effect. */
5
+ export interface NativeEpisodeRecorder {
6
+ readonly schemaVersion: 1;
7
+ readonly runtime: 'peer-native';
8
+ readonly execution: SessionExecutionIdentity;
9
+ readonly recorder: NonNullable<SessionControlOperation['recorder']>;
10
+ }
2
11
  export interface ProjectWorkBudgetLimits {
3
12
  readonly schemaVersion?: 2;
4
13
  readonly source: string;
@@ -144,13 +153,25 @@ export interface ProjectWorkReceipt {
144
153
  readonly requests?: number;
145
154
  readonly modelProviderId?: string;
146
155
  readonly checkpointRef?: string;
156
+ readonly nativeRecorder?: NativeEpisodeRecorder;
157
+ /** Unvalidated stored snapshot; admit v1 before consuming billing facts. */
158
+ readonly nativeUsage?: unknown;
159
+ /** Loop admission ended; this is not a stop receipt. */
160
+ readonly nativeLoopFinished?: true;
147
161
  readonly pendingTools?: readonly {
148
162
  readonly toolCallId: string | null;
149
163
  readonly capabilityId: string | null;
150
164
  readonly verificationSessionId?: string;
165
+ readonly nativeRecorder?: NativeEpisodeRecorder;
166
+ readonly nativeProcess?: NativeOwnedProcess;
151
167
  }[];
152
168
  }>>;
153
169
  readonly reconciledDispatches?: readonly VerificationDispatchReconciliation[];
170
+ /** Keep unknown/future records intact until a compatible billing owner acts. */
171
+ readonly nativeUsagePending?: Readonly<Record<string, {
172
+ readonly snapshot: unknown;
173
+ readonly nativeRecorder: unknown;
174
+ }>>;
154
175
  readonly settledDispatches?: readonly SettledDelegationDispatch[];
155
176
  readonly uncertainDispatches?: readonly {
156
177
  readonly attemptId: string;
@@ -158,6 +179,8 @@ export interface ProjectWorkReceipt {
158
179
  readonly toolCallId: string | null;
159
180
  readonly capabilityId: string | null;
160
181
  readonly verificationSessionId?: string;
182
+ readonly nativeRecorder?: NativeEpisodeRecorder;
183
+ readonly nativeProcess?: NativeOwnedProcess;
161
184
  }[];
162
185
  };
163
186
  readonly stopScope: 'reply' | 'work';
@@ -0,0 +1,3 @@
1
+ export declare const WORK_HOOK_SEMANTIC_FLOOR = 14;
2
+ /** Shape only. OS observation, ownership and business effects require Host evidence. */
3
+ export declare function nativeWorkHasHookFacts(work: unknown): boolean;
@@ -0,0 +1,76 @@
1
+ import { isHookObservation } from "./hook-observation.js";
2
+ import { nativeProcessEnvelopeValid } from "./native-process.js";
3
+ import { normalizeSessionExecutionIdentity } from "./session-control.js";
4
+ export const WORK_HOOK_SEMANTIC_FLOOR = 14;
5
+ const maxHandles = 256;
6
+ const invalid = () => { throw new Error('native_work_hooks_invalid'); };
7
+ const record = (input) => input !== null && typeof input === 'object' && !Array.isArray(input) ? input : undefined;
8
+ const requiredId = (input) => typeof input === 'string' && input.length > 0
9
+ && new TextEncoder().encode(input).length <= 200;
10
+ const ownerKeys = ['pid', 'pidStart', 'bootId', 'hostId', 'acquiredAt'];
11
+ /** Shape only. OS observation, ownership and business effects require Host evidence. */
12
+ export function nativeWorkHasHookFacts(work) {
13
+ const budget = record(record(work)?.budget);
14
+ const pending = Object.values(record(budget?.attempts) ?? {}).flatMap(attempt => {
15
+ const pending = record(attempt)?.pendingTools;
16
+ return Array.isArray(pending) ? pending : [];
17
+ });
18
+ const rows = pending.concat(Array.isArray(budget?.uncertainDispatches) ? budget.uncertainDispatches : []);
19
+ const ids = new Set();
20
+ let found = false;
21
+ for (const input of rows) {
22
+ const row = record(input);
23
+ if (!row || !Object.hasOwn(row, 'nativeHooks'))
24
+ continue;
25
+ const hooks = record(row.nativeHooks);
26
+ const recorder = record(row.nativeRecorder);
27
+ const owner = record(recorder?.recorder);
28
+ const execution = normalizeSessionExecutionIdentity(recorder?.execution);
29
+ const provider = record(row.nativeProcess);
30
+ const intent = record(hooks?.intent);
31
+ if (!hooks || Object.keys(hooks).some(key => !['schemaVersion', 'providerPhase', 'handles', 'intent', 'grant'].includes(key))
32
+ || Object.hasOwn(hooks, 'intent') && (!intent || Object.keys(intent).length !== 2
33
+ || !requiredId(intent.messageId) || /[\u0000-\u001f\u007f-\u009f]/u.test(intent.messageId)
34
+ || typeof intent.argsDigest !== 'string' || !/^[a-f0-9]{64}$/.test(intent.argsDigest))
35
+ || hooks.schemaVersion !== 1
36
+ || !['prepared', 'dispatching'].some(phase => phase === hooks.providerPhase)
37
+ || !Array.isArray(hooks.handles) || hooks.handles.length > maxHandles
38
+ || recorder?.schemaVersion !== 1 || recorder.runtime !== 'peer-native' || !owner || !execution
39
+ || !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.pid > 2147483647
40
+ || ownerKeys.slice(1).some(key => typeof owner[key] !== 'string' || !owner[key].length
41
+ || new TextEncoder().encode(owner[key]).length > 8192)
42
+ || !requiredId(row.toolCallId) || !requiredId(row.dispatchId)
43
+ || hooks.providerPhase === 'prepared' && Object.hasOwn(row, 'nativeProcess'))
44
+ return invalid();
45
+ if (Object.hasOwn(hooks, 'grant')) {
46
+ const grant = record(hooks.grant);
47
+ if (hooks.providerPhase !== 'dispatching' || !intent || !grant || grant.granted !== true
48
+ || grant.toolCallId !== row.toolCallId || grant.duration !== 'once'
49
+ || typeof grant.grantId !== 'string' || grant.grantId.length === 0)
50
+ return invalid();
51
+ }
52
+ found = true;
53
+ for (const input of hooks.handles) {
54
+ const hook = record(input);
55
+ const process = record(hook?.process);
56
+ const processOwner = record(process?.owner);
57
+ const processExecution = normalizeSessionExecutionIdentity(process?.execution);
58
+ if (!hook || Object.keys(hook).some(key => !['event', 'ruleDigest', 'process', 'observation'].includes(key))
59
+ || !['PreToolUse', 'PostToolUse'].some(event => event === hook.event)
60
+ || hooks.providerPhase === 'prepared' && hook.event === 'PostToolUse'
61
+ || typeof hook.ruleDigest !== 'string' || !/^[a-f0-9]{64}$/.test(hook.ruleDigest)
62
+ || !process || !nativeProcessEnvelopeValid(process) || !processOwner || !processExecution
63
+ || ownerKeys.some(key => processOwner[key] !== owner[key])
64
+ || JSON.stringify(processExecution) !== JSON.stringify(execution)
65
+ || process.toolCallId !== row.toolCallId || process.dispatchId !== row.dispatchId
66
+ || process.generation > 1
67
+ || ids.size >= maxHandles || ids.has(process.handleId) || process.handleId === provider?.handleId
68
+ || (process.stopObservation === 'owned_completion'
69
+ ? !isHookObservation(hook.observation, hook.event, hook.ruleDigest, process.handleId)
70
+ : Object.hasOwn(hook, 'observation')))
71
+ return invalid();
72
+ ids.add(process.handleId);
73
+ }
74
+ }
75
+ return found;
76
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/protocol",
3
- "version": "0.1.0-rc.41",
3
+ "version": "0.1.0-rc.43",
4
4
  "description": "Shared host-neutral protocol contracts for Peer Agent runtimes and clients.",
5
5
  "type": "module",
6
6
  "license": "MIT",