@peer-agent/protocol 0.1.0-rc.40 → 0.1.0-rc.42

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.
@@ -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.40",
3
+ "version": "0.1.0-rc.42",
4
4
  "description": "Shared host-neutral protocol contracts for Peer Agent runtimes and clients.",
5
5
  "type": "module",
6
6
  "license": "MIT",