@peer-agent/protocol 0.1.0-rc.23 → 0.1.0-rc.25

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.
@@ -0,0 +1,29 @@
1
+ import type { LocalAccessLevel } from './index.ts';
2
+ /** Device-local user authority. Never supplied by a model or copied into a worker profile. */
3
+ export interface BotAccessPolicy {
4
+ readonly workspaceId: string;
5
+ readonly conversationId: string;
6
+ readonly accessLevel: LocalAccessLevel;
7
+ readonly revision: number;
8
+ readonly updatedAt: string;
9
+ readonly source: 'legacy_migration' | 'new_bot' | 'local_ui';
10
+ }
11
+ export interface BotAccessPolicyReadRequest {
12
+ readonly workspaceId?: string;
13
+ readonly conversationId?: string;
14
+ }
15
+ export interface BotAccessPolicyUpdateRequest {
16
+ readonly workspaceId: string;
17
+ readonly expectedRevision: number;
18
+ readonly accessLevel: LocalAccessLevel;
19
+ }
20
+ export type BotAccessPolicyResult = {
21
+ readonly ok: true;
22
+ readonly policy: BotAccessPolicy | null;
23
+ readonly inherited: boolean;
24
+ readonly botName?: string;
25
+ } | {
26
+ readonly ok: false;
27
+ readonly code: 'INVALID_INPUT' | 'NOT_FOUND' | 'OUT_OF_SCOPE' | 'POLICY_CONFLICT' | 'POLICY_UNAVAILABLE' | 'PROJECT_AGENT_DISABLED';
28
+ readonly policy?: BotAccessPolicy;
29
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ /** Independent read sections; availability never grants execution authority. */
2
+ export type BotConversationReadView = 'interactions' | 'cards';
3
+ export interface BotConversationReadAvailability {
4
+ readonly section: 'messages' | 'cards';
5
+ readonly state: 'ready' | 'rebuilding' | 'unavailable';
6
+ readonly sourceVersion?: string;
7
+ readonly code?: string;
8
+ }
9
+ /** Small durable accounting event; full results and provider checkpoints remain referenced. */
10
+ export interface CoordinationUsageObservation {
11
+ readonly kind: 'usage_observed';
12
+ readonly workId: string;
13
+ readonly observationId: string;
14
+ readonly tokens: number | null;
15
+ readonly costUsd: number | null;
16
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Project-agent delegation contracts. Pure projections only; nothing here runs a tool.
3
- * The user-visible conclusion of a work session is projectGoalPlan's conclusion.
3
+ * The user-visible conclusion of a work session is `decideLifecycle`'s conclusion.
4
4
  */
5
5
  import type { ModelSelectionSnapshot } from './model-routing.ts';
6
- import { type GoalPlanProjectionSnapshot, type TaskOverviewItem } from './task-overview.ts';
6
+ import { type ExecutionOwnership, type GoalPlanProjectionSnapshot, type TaskOverviewItem } from './task-overview.ts';
7
7
  export type WorkSessionStatus = 'paused' | 'queued' | 'starting' | 'running' | 'waiting_user' | 'waiting_agent' | 'stopping' | 'awaiting_outcome' | 'verifying' | 'result_ready' | 'accepted' | 'failed' | 'cancelled' | 'superseded';
8
8
  export declare const WORK_SESSION_STATUSES: readonly ["paused", "queued", "starting", "running", "waiting_user", "waiting_agent", "stopping", "awaiting_outcome", "verifying", "result_ready", "accepted", "failed", "cancelled", "superseded"];
9
9
  export type InputSurface = 'desktop' | 'quick_chat' | 'tui' | 'remote';
@@ -64,8 +64,11 @@ export interface WorkSessionConversationMeta extends SessionQueueFacts {
64
64
  readonly accepted?: boolean;
65
65
  readonly verifying?: boolean;
66
66
  readonly phase?: 'starting' | 'verifying' | 'paused';
67
+ /** 进程内执行所有权(runtime 采集);缺省表示该入口尚未接入所有权事实。 */
68
+ readonly executionOwnership?: ExecutionOwnership;
67
69
  }
68
70
  export interface WorkSession extends SessionQueueFacts {
71
+ readonly verificationProgress?: VerificationProgress;
69
72
  readonly completionReviewRequired?: boolean;
70
73
  readonly resultConfirmationRequired?: boolean;
71
74
  readonly coordination?: import('./delegation-coordination.ts').CoordinationSessionFacts;
@@ -77,6 +80,8 @@ export interface WorkSession extends SessionQueueFacts {
77
80
  readonly actionRight: TaskOverviewItem['actionRight'];
78
81
  readonly nextAction: TaskOverviewItem['nextAction'];
79
82
  readonly statusLabel: string;
83
+ /** 是否可取消;由生命周期决策统一给出,renderer 不再自行推断。 */
84
+ readonly cancelable?: boolean;
80
85
  readonly needsYouReason?: TaskOverviewItem['needsYouReason'];
81
86
  readonly spawnedAt: string;
82
87
  readonly conversationId?: string;
@@ -117,11 +122,19 @@ export interface AgentMessage {
117
122
  readonly text: string;
118
123
  readonly at: string;
119
124
  }
125
+ export interface VerificationProgress {
126
+ readonly continuationId: string;
127
+ readonly startedAt: string;
128
+ readonly lastProgressAt: string;
129
+ readonly observationCount: number;
130
+ readonly phase: 'ready' | 'requesting' | 'tools' | 'completed';
131
+ }
120
132
  export interface AgentActivity {
133
+ readonly verificationProgress?: VerificationProgress;
121
134
  readonly eventId: string;
122
135
  readonly sessionId: string;
123
136
  readonly name: string;
124
- readonly state: 'queued' | 'started' | 'update' | 'question' | 'answer' | 'reported' | 'verified' | 'ended' | 'cancelled' | 'blocked';
137
+ readonly state: 'queued' | 'started' | 'update' | 'question' | 'answer' | 'reported' | 'verified' | 'verifying' | 'ended' | 'cancelled' | 'blocked';
125
138
  }
126
139
  export type JsonValue = null | string | number | boolean | readonly JsonValue[] | {
127
140
  readonly [key: string]: JsonValue;
@@ -324,6 +337,7 @@ export interface ProjectInput {
324
337
  }
325
338
  export type PendingApprovalState = 'open' | 'approved' | 'denied' | 'expired' | 'stale' | 'cancelled';
326
339
  export interface PendingApproval {
340
+ readonly policyRevision?: string;
327
341
  readonly imageReadScope?: import('./local-image.ts').LocalImagePermissionScope;
328
342
  readonly imageReadGrant?: import('./local-image.ts').ImageReadGrant;
329
343
  readonly approvalId: string;
@@ -340,7 +354,7 @@ export interface PendingApproval {
340
354
  readonly createdAt: string;
341
355
  readonly state: PendingApprovalState;
342
356
  readonly deadlineAt?: string;
343
- readonly decisionReason?: 'permission_cancelled' | 'permission_timeout' | 'permission_unavailable' | 'local_user_denied';
357
+ readonly decisionReason?: 'permission_cancelled' | 'permission_timeout' | 'permission_unavailable' | 'local_user_denied' | 'permission_policy_changed';
344
358
  readonly decidedAt?: string;
345
359
  readonly decidedBy?: 'local_ui' | 'policy';
346
360
  }
@@ -1,5 +1,8 @@
1
- import { deriveSessionFacts } from "./session-facts.js";
2
- import { projectGoalPlan, } from "./task-overview.js";
1
+ /**
2
+ * Project-agent delegation contracts. Pure projections only; nothing here runs a tool.
3
+ * The user-visible conclusion of a work session is `decideLifecycle`'s conclusion.
4
+ */
5
+ import { decideLifecycle, } from "./task-overview.js";
3
6
  export const WORK_SESSION_STATUSES = ['paused', 'queued', 'starting', 'running', 'waiting_user', 'waiting_agent', 'stopping', 'awaiting_outcome', 'verifying',
4
7
  'result_ready', 'accepted', 'failed', 'cancelled', 'superseded'];
5
8
  function fnv1a(text) {
@@ -40,39 +43,51 @@ export function createDelegationEvent(input) {
40
43
  payload,
41
44
  };
42
45
  }
43
- function delegationStatus(snapshot, meta, projected) {
44
- return deriveSessionFacts({ status: snapshot.status, runnerStatus: snapshot.runnerStatus,
45
- cancellationPhase: meta.origin.cancellation?.phase,
46
- takeoverPhase: meta.coordination?.phase === 'awaiting_outcome' ? 'awaiting_outcome' : meta.origin.takeover?.phase,
47
- accepted: meta.accepted === true || (snapshot.status === 'completed' && meta.acceptance !== 'confirm'
48
- && meta.accepted === undefined && !meta.verifying && !snapshot.runnerStatus),
49
- superseded: Boolean(meta.supersededBy), phase: meta.phase,
50
- needsUser: snapshot.status === 'awaiting_approval' || snapshot.needsUser === true, verificationActive: meta.verifying === true,
51
- blockedReason: snapshot.agentWaiting ? 'waiting_parent_agent' : snapshot.blockedReason,
52
- }).status;
53
- }
54
46
  /**
55
47
  * Project a GoalPlan snapshot into a work session.
56
48
  * actionRight / nextAction / statusLabel come from projectGoalPlan, so the two projections cannot disagree.
57
49
  * A paused plan has no delegation status of its own; it is queued, and the visible conclusion stays paused.
58
50
  */
59
51
  export function projectWorkSession(plan, conversationMeta) {
60
- const projected = projectGoalPlan(plan);
61
- const status = delegationStatus(plan, conversationMeta, projected);
62
- const parentFollowing = status === 'waiting_agent' || status === 'verifying';
63
- const transitioning = ['stopping', 'awaiting_outcome'].includes(status) || conversationMeta.origin.takeover?.phase === 'stopping';
52
+ const projected = decideLifecycle(plan, {
53
+ ...(conversationMeta.executionOwnership ? { executionOwnership: conversationMeta.executionOwnership } : {}),
54
+ // `delegated` 必须是真实事实;不能用"这是工作会话"反推,否则会改写非委派历史语义。
55
+ ...(plan.delegated === true ? { delegated: true } : {}),
56
+ ...(conversationMeta.acceptance ? { acceptance: conversationMeta.acceptance } : {}),
57
+ accepted: conversationMeta.accepted === true ||
58
+ (plan.delegated !== true &&
59
+ plan.status === 'completed' &&
60
+ conversationMeta.acceptance !== 'confirm' &&
61
+ conversationMeta.accepted === undefined &&
62
+ !conversationMeta.verifying &&
63
+ !plan.runnerStatus),
64
+ superseded: Boolean(conversationMeta.supersededBy),
65
+ needsUser: plan.status === 'awaiting_approval' || plan.needsUser === true,
66
+ verificationActive: conversationMeta.verifying === true,
67
+ ...(conversationMeta.phase ? { phase: conversationMeta.phase } : {}),
68
+ blockedReason: plan.agentWaiting ? 'waiting_parent_agent' : plan.blockedReason,
69
+ ...(conversationMeta.origin.cancellation?.phase
70
+ ? { cancellationPhase: conversationMeta.origin.cancellation.phase }
71
+ : {}),
72
+ ...(conversationMeta.coordination?.phase === 'awaiting_outcome'
73
+ ? { takeoverPhase: 'awaiting_outcome' }
74
+ : conversationMeta.origin.takeover?.phase
75
+ ? { takeoverPhase: conversationMeta.origin.takeover.phase }
76
+ : {}),
77
+ });
78
+ const status = projected.status;
64
79
  return {
65
80
  sessionId: conversationMeta.sessionId ?? plan.conversationId ?? plan.planId,
66
81
  workspaceId: conversationMeta.workspaceId,
67
82
  title: plan.title,
68
83
  planId: plan.planId,
69
84
  status,
70
- actionRight: transitioning || parentFollowing ? 'peer_advancing' : projected.actionRight,
71
- nextAction: transitioning || parentFollowing ? 'none' : projected.nextAction,
72
- statusLabel: status === 'stopping' ? '正在停止' : status === 'awaiting_outcome' ? '执行结果待核实'
73
- : conversationMeta.origin.takeover?.phase === 'stopping' ? '正在接手'
74
- : status === 'waiting_agent' ? '由主 Bot 跟进' : status === 'verifying' ? '核验中' : projected.statusLabel,
75
- ...(!transitioning && !parentFollowing && projected.needsYouReason ? { needsYouReason: projected.needsYouReason } : {}),
85
+ // 直接消费同一份决策;这里再改写就等于第二套状态机。
86
+ actionRight: projected.actionRight,
87
+ nextAction: projected.nextAction,
88
+ statusLabel: projected.statusLabel,
89
+ cancelable: projected.cancelable,
90
+ ...(projected.needsYouReason ? { needsYouReason: projected.needsYouReason } : {}),
76
91
  ...(conversationMeta.coordination ? { coordination: conversationMeta.coordination } : {}),
77
92
  spawnedAt: conversationMeta.spawnedAt ?? plan.updatedAt ?? '',
78
93
  ...(conversationMeta.conversationId ? { conversationId: conversationMeta.conversationId } : {}),
package/dist/goal.d.ts CHANGED
@@ -603,6 +603,11 @@ export interface GoalRunnerState {
603
603
  readonly fingerprint?: string;
604
604
  readonly repeats?: number;
605
605
  readonly progressFacts?: readonly string[];
606
+ readonly startedAt?: string;
607
+ readonly lastProgressAt?: string;
608
+ readonly observationCount?: number;
609
+ readonly observationFacts?: readonly string[];
610
+ readonly formatRequests?: number;
606
611
  };
607
612
  readonly enabled: boolean;
608
613
  readonly status: GoalRunnerStatus;
package/dist/index.d.ts CHANGED
@@ -17,6 +17,7 @@ export type { RemoteReadRequest, RemoteReadContext, RemoteReadRejection, RemoteR
17
17
  export { REMOTE_PROJECT_LIMITS, parseRemoteProjectRequest, admitRemoteProject, parseRemoteDelegationProjection } from './remote-access.ts';
18
18
  export type { RemoteProjectGrant, RemoteProjectRequest, RemoteProjectContext, RemoteProjectRejection, RemoteProjectAdmission, RemoteDelegationProjection } from './remote-access.ts';
19
19
  export type LocalAccessLevel = 'ask_before_local' | 'session_local' | 'restricted_local' | 'full_local';
20
+ export type { BotAccessPolicy, BotAccessPolicyReadRequest, BotAccessPolicyUpdateRequest, BotAccessPolicyResult } from './bot-access-policy.ts';
20
21
  export type { ConversationLifetimeUsage, ProviderRequestUsage, RuntimeTurnUsage, UsageAmounts, UsageScope, } from './usage-accounting.ts';
21
22
  export type CapabilityRiskLevel = 'L0_inert' | 'L1_local_read' | 'L2_local_write' | 'L3_external_write' | 'L4_privileged' | 'L5_destructive';
22
23
  export type DataLevel = 'D0_public' | 'D1_internal' | 'D2_sensitive' | 'D3_private' | 'D4_regulated';
@@ -753,6 +754,8 @@ export interface ClientToolCallPollResult {
753
754
  }
754
755
  export type PermissionDuration = 'once' | 'task' | 'session' | 'scope' | 'persistent' | 'denied';
755
756
  export interface PermissionGrant {
757
+ /** Host-issued policy version; audit provenance, never a client authority token. */
758
+ readonly policyRevision?: string;
756
759
  readonly grantId: string;
757
760
  readonly toolCallId: string;
758
761
  readonly granted: boolean;
@@ -892,3 +895,4 @@ export * from './objectives.ts';
892
895
  export * from './remote-access-settings.ts';
893
896
  export type { BotModelSelectionUpdateRequest, BotModelSelectionUpdateResult } from './bot-model-selection.ts';
894
897
  export * from './local-image.ts';
898
+ export * from './bot-conversation-read.ts';
package/dist/index.js CHANGED
@@ -42,3 +42,4 @@ export * from "./project.js";
42
42
  export * from "./objectives.js";
43
43
  export * from "./remote-access-settings.js";
44
44
  export * from "./local-image.js";
45
+ export * from "./bot-conversation-read.js";
@@ -34,6 +34,7 @@ export interface LocalImagePermissionScope {
34
34
  }
35
35
  /** Local host-issued exact-image read authority; no pixels are persisted. */
36
36
  export interface ImageReadGrant {
37
+ policyRevision?: string;
37
38
  schemaVersion: 1;
38
39
  grantId: string;
39
40
  workspaceId: string | null;
@@ -1,10 +1,15 @@
1
- import type { WorkSessionStatus } from './delegation.ts';
1
+ import { type ExecutionOwnership, type LifecycleDecision } from './task-overview.ts';
2
+ export type { ExecutionOwnership, LifecycleDecision, LifecycleFacts } from './task-overview.ts';
2
3
  export interface SessionFactSnapshot {
3
- readonly status: WorkSessionStatus;
4
+ readonly status: LifecycleDecision['status'];
4
5
  readonly verificationActive: boolean;
5
6
  readonly needsUser: boolean;
6
7
  readonly blockedReason?: string;
7
8
  }
9
+ /**
10
+ * 兼容入口:把扁平事实交给唯一的生命周期决策器。
11
+ * 旧的直接判定逻辑已删除,`status / needsUser / blockedReason` 全部来自 `decideLifecycle`。
12
+ */
8
13
  export declare function deriveSessionFacts(input: {
9
14
  status?: string;
10
15
  phase?: string;
@@ -14,6 +19,8 @@ export declare function deriveSessionFacts(input: {
14
19
  needsUser?: boolean;
15
20
  blockedReason?: string;
16
21
  verificationActive?: boolean;
22
+ interrupted?: boolean;
17
23
  cancellationPhase?: string;
18
24
  takeoverPhase?: string;
25
+ executionOwnership?: ExecutionOwnership;
19
26
  }): SessionFactSnapshot;
@@ -1,41 +1,32 @@
1
+ import { decideLifecycle, } from "./task-overview.js";
2
+ /**
3
+ * 兼容入口:把扁平事实交给唯一的生命周期决策器。
4
+ * 旧的直接判定逻辑已删除,`status / needsUser / blockedReason` 全部来自 `decideLifecycle`。
5
+ */
1
6
  export function deriveSessionFacts(input) {
2
- const verificationActive = input.verificationActive === true;
3
- let status;
4
- if (input.status === 'cancelled')
5
- status = 'cancelled';
6
- else if (input.status === 'failed')
7
- status = 'failed';
8
- else if (input.accepted)
9
- status = 'accepted';
10
- else if (input.cancellationPhase === 'awaiting_outcome' || input.takeoverPhase === 'awaiting_outcome')
11
- status = 'awaiting_outcome';
12
- else if (input.cancellationPhase === 'stopping')
13
- status = 'stopping';
14
- else if (input.takeoverPhase === 'stopping')
15
- status = 'starting';
16
- else if (input.superseded && input.status !== 'completed')
17
- status = 'superseded';
18
- else if ((input.phase === 'paused' || input.runnerStatus === 'paused') && input.status !== 'completed')
19
- status = 'paused';
20
- else if (input.needsUser || input.runnerStatus === 'waiting_user')
21
- status = 'waiting_user';
22
- else if (input.blockedReason === 'waiting_parent_agent' && input.phase !== 'paused' && !input.superseded && input.runnerStatus !== 'paused')
23
- status = 'waiting_agent';
24
- else if (verificationActive)
25
- status = 'verifying';
26
- // A technical blocker is work for the parent Agent. It is not a human question.
27
- else if (input.runnerStatus === 'blocked')
28
- status = 'waiting_agent';
29
- else if (input.status === 'completed' && ['running', 'starting', 'waiting_provider', 'resuming_after_compaction'].includes(input.runnerStatus || ''))
30
- status = 'running';
31
- else if (input.status === 'completed')
32
- status = 'result_ready';
33
- else if (input.phase === 'starting')
34
- status = 'starting';
35
- else if (['approved', 'accepted', 'paused', 'interrupted'].includes(input.status || '') || input.phase === 'queued')
36
- status = 'queued';
37
- else
38
- status = 'running';
39
- return { status, verificationActive: status === 'verifying', needsUser: status === 'waiting_user',
40
- ...(input.blockedReason ? { blockedReason: input.blockedReason } : {}) };
7
+ const snapshot = {
8
+ conversationId: '',
9
+ title: '',
10
+ planId: '',
11
+ status: (input.status ?? 'executing'),
12
+ ...(input.runnerStatus ? { runnerStatus: input.runnerStatus } : {}),
13
+ };
14
+ const decision = decideLifecycle(snapshot, {
15
+ ...(input.executionOwnership ? { executionOwnership: input.executionOwnership } : {}),
16
+ ...(input.phase ? { phase: input.phase } : {}),
17
+ ...(input.accepted !== undefined ? { accepted: input.accepted } : {}),
18
+ ...(input.superseded !== undefined ? { superseded: input.superseded } : {}),
19
+ ...(input.needsUser !== undefined ? { needsUser: input.needsUser } : {}),
20
+ ...(input.blockedReason ? { blockedReason: input.blockedReason } : {}),
21
+ ...(input.verificationActive !== undefined ? { verificationActive: input.verificationActive } : {}),
22
+ ...(input.interrupted !== undefined ? { interrupted: input.interrupted } : {}),
23
+ ...(input.cancellationPhase ? { cancellationPhase: input.cancellationPhase } : {}),
24
+ ...(input.takeoverPhase ? { takeoverPhase: input.takeoverPhase } : {}),
25
+ });
26
+ return {
27
+ status: decision.status,
28
+ verificationActive: decision.verificationActive,
29
+ needsUser: decision.needsUser,
30
+ ...(decision.blockedReason ? { blockedReason: decision.blockedReason } : {}),
31
+ };
41
32
  }
@@ -1,3 +1,4 @@
1
+ import type { WorkSessionStatus } from './delegation.ts';
1
2
  /**
2
3
  * TaskOverview 行动权投影契约 —— Peer 2.0 阶段 0 协议层。
3
4
  *
@@ -103,6 +104,11 @@ export interface TaskOverviewItem {
103
104
  readonly source: TaskOverviewSourceKind;
104
105
  /** 行动权归属。 */
105
106
  readonly actionRight: TaskActionRight;
107
+ /**
108
+ * 本投影是否真的可取消(生命周期决策给出)。
109
+ * 缺省表示来自尚未接入决策的旧入口;renderer 不得自行再写一套生命周期规则。
110
+ */
111
+ readonly cancelable?: boolean;
106
112
  /** needs_you 细分桶;仅 actionRight === 'needs_you' 时有值。 */
107
113
  readonly needsYouReason?: TaskNeedsYouReason;
108
114
  /** 下一步动作标识。 */
@@ -304,6 +310,15 @@ export interface GoalPlanProjectionSnapshot {
304
310
  * 完成即终态,合回/自检未结束仍走 peer_advancing 或 needs_you。
305
311
  */
306
312
  readonly accepted?: boolean;
313
+ /**
314
+ * 进程内执行所有权(runtime → protocol 事实)。
315
+ * 只有 `live` 能证明"还在跑";重启后缺 token 只能 `unknown`,既不是活体也不是已结束。
316
+ */
317
+ readonly executionOwnership?: ExecutionOwnership;
318
+ /** 是否委派会话;委派任务的 accepted 只能来自真实落盘的验收结论。 */
319
+ readonly delegated?: boolean;
320
+ /** 归一化后的活体执行事实,仅由 decideLifecycle 计算,调用方不得直接写。 */
321
+ readonly liveExecution?: boolean;
307
322
  /** 有代码副作用时,完成门之后还要质量自检过线才能进终态。 */
308
323
  readonly requiresQualityReview?: boolean;
309
324
  readonly qualityReviewStatus?: 'reviewing' | 'passed' | 'failed';
@@ -361,6 +376,59 @@ export interface ShellBackgroundProjectionSnapshot {
361
376
  readonly toolCallId?: string;
362
377
  readonly conversationId?: string;
363
378
  }
379
+ interface ProjectionDecision {
380
+ readonly actionRight: TaskActionRight;
381
+ readonly needsYouReason?: TaskNeedsYouReason;
382
+ readonly nextAction: TaskNextAction;
383
+ readonly statusLabel: string;
384
+ readonly actionLabel: string;
385
+ }
386
+ /**
387
+ * 进程内执行所有权。`live` 只能由本进程持有的执行/核验 token 产生;
388
+ * 重启后持久化标记只能算 `unknown`(不许当活体,也不许当已结束)。
389
+ */
390
+ export type ExecutionOwnership = 'live' | 'ended' | 'unknown';
391
+ /**
392
+ * 生命周期事实:runtime 只提供事实,不提供结论。
393
+ * `decideLifecycle` 是 `status / statusLabel / actionRight / nextAction / cancelable`
394
+ * 的唯一出口;任何适配器都不得自行改写生命周期结论。
395
+ */
396
+ export interface LifecycleFacts {
397
+ readonly executionOwnership?: ExecutionOwnership;
398
+ readonly phase?: string;
399
+ readonly delegated?: boolean;
400
+ readonly acceptance?: string;
401
+ readonly accepted?: boolean;
402
+ readonly superseded?: boolean;
403
+ readonly needsUser?: boolean;
404
+ /** 未消费的执行中断是当前行动权事实,优先于 completed/结果就绪。 */
405
+ readonly interrupted?: boolean;
406
+ readonly verificationActive?: boolean;
407
+ readonly blockedReason?: string;
408
+ readonly cancellationPhase?: string;
409
+ readonly takeoverPhase?: string;
410
+ readonly coordinationPhase?: string;
411
+ }
412
+ export interface LifecycleDecision extends ProjectionDecision {
413
+ readonly status: WorkSessionStatus;
414
+ readonly cancelable: boolean;
415
+ readonly needsUser: boolean;
416
+ readonly verificationActive: boolean;
417
+ readonly blockedReason?: string;
418
+ }
419
+ /**
420
+ * 生命周期唯一决策。
421
+ *
422
+ * 关键不变量:
423
+ * - 活 token 不能压过等待用户/父代理、核验、停止中/结果未知、中断等更具体事实;
424
+ * - 持久化 `runnerStatus` 在 ownership=unknown 时不得当作"还在跑";
425
+ * - `accepted` 只来自真实验收事实(本函数不制造 accepted);
426
+ * - 返回的字段必须被所有投影直接消费,不得二次推导。
427
+ *
428
+ * 过渡兼容:不传 `executionOwnership` 的旧入口按 `unknown` 处理——
429
+ * `runner.status` 字符串本身不能证明"还在跑";真实入口(S2/S3)应显式传入 live/ended/unknown。
430
+ */
431
+ export declare function decideLifecycle(snapshot: GoalPlanProjectionSnapshot, facts?: LifecycleFacts): LifecycleDecision;
364
432
  /** Conversation → 无计划讨论态(工作台动线 §15)。 */
365
433
  /**
366
434
  * 会话是否对首页「正在讨论」可见(未读)。
@@ -424,3 +492,4 @@ export declare function areTaskOverviewItemsEqual(current: TaskOverviewItem, nex
424
492
  * 首页无 conversationId,只能整表重拉;复用后单路进度不会拖垮其余卡。
425
493
  */
426
494
  export declare function reuseUnchangedTaskOverviewItems(current: readonly TaskOverviewItem[], next: readonly TaskOverviewItem[]): TaskOverviewItem[];
495
+ export {};
@@ -1,24 +1,222 @@
1
+ import { projectGoalTiming } from "./goal.js";
2
+ /** 仍在占用执行体的 runner 状态(持久化字符串本身不构成活体证据)。 */
3
+ const ACTIVE_EXECUTION_RUNNER_STATUSES = new Set([
4
+ 'running',
5
+ 'starting',
6
+ 'waiting_provider',
7
+ 'resuming_after_compaction',
8
+ 'exploring',
9
+ ]);
10
+ /** 终态与"结果待核实"不可取消:停止中/结果未知也不能靠重复取消恢复。 */
11
+ const NON_CANCELABLE_STATUSES = new Set([
12
+ 'accepted',
13
+ 'failed',
14
+ 'cancelled',
15
+ 'superseded',
16
+ 'result_ready',
17
+ 'stopping',
18
+ 'awaiting_outcome',
19
+ ]);
1
20
  /**
2
- * TaskOverview 行动权投影契约 —— Peer 2.0 阶段 0 协议层。
3
- *
4
- * 设计依据:peer-knowledge design/product/peer-2-0-gap-analysis.md §11。
21
+ * 生命周期唯一决策。
5
22
  *
6
- * 核心命题:首页/任务/历史三页面不是第二份任务数据库,而是
7
- * GoalPlan / GoalRunner / Automation 三套状态机按「下一步行动权」
8
- * 形成的动态投影。本文件是该投影的唯一事实来源(single source of truth)。
23
+ * 关键不变量:
24
+ * - 活 token 不能压过等待用户/父代理、核验、停止中/结果未知、中断等更具体事实;
25
+ * - 持久化 `runnerStatus` 在 ownership=unknown 时不得当作"还在跑";
26
+ * - `accepted` 只来自真实验收事实(本函数不制造 accepted);
27
+ * - 返回的字段必须被所有投影直接消费,不得二次推导。
9
28
  *
10
- * 治理红线(AGENTS.md):
11
- * - renderer 只消费本模块输出的投影结果,不自行解析 GoalPlanStatus/
12
- * AutomationRunStatus 推断行动权,不在前端维护任务状态副本。
13
- * - 映射规则见 §11.3:判定顺序从上到下、首个命中生效;本模块用
14
- * projectGoalPlan / projectAutomationRun 两个纯函数实现该顺序。
29
+ * 过渡兼容:不传 `executionOwnership` 的旧入口按 `unknown` 处理——
30
+ * `runner.status` 字符串本身不能证明"还在跑";真实入口(S2/S3)应显式传入 live/ended/unknown。
31
+ */
32
+ export function decideLifecycle(snapshot, facts = {}) {
33
+ const declaredOwnership = facts.executionOwnership ?? snapshot.executionOwnership;
34
+ const ownership = declaredOwnership ?? 'unknown';
35
+ const persistedRunner = snapshot.runnerStatus;
36
+ const persistedActive = persistedRunner ? ACTIVE_EXECUTION_RUNNER_STATUSES.has(persistedRunner) : false;
37
+ const liveExecution = ownership === 'live' && (persistedActive || persistedRunner === undefined);
38
+ // 持久化 runner 状态不是活体证据:unknown(重启遗留)和 ended(活流已结束、数据滞后)
39
+ // 都不能凭字符串冒充 live。waiting_user 的待消费问题按 ADR 100 保留。
40
+ const stalePersistedRunner = persistedActive && ownership !== 'live';
41
+ const runnerStatus = stalePersistedRunner ? undefined : persistedRunner;
42
+ const { runnerStatus: _rawRunnerStatus, ...snapshotRest } = snapshot;
43
+ const canonical = {
44
+ ...snapshotRest,
45
+ ...(runnerStatus ? { runnerStatus } : {}),
46
+ liveExecution,
47
+ };
48
+ const decision = decideGoalPlan(canonical);
49
+ const accepted = facts.accepted ?? snapshot.accepted;
50
+ const needsUserFacts = facts.needsUser === true ||
51
+ snapshot.needsUser === true ||
52
+ snapshot.status === 'awaiting_approval';
53
+ const verificationActive = facts.verificationActive === true;
54
+ const blockedReason = facts.blockedReason ?? snapshot.blockedReason;
55
+ const interrupted = facts.interrupted ?? snapshot.interrupted === true;
56
+ const delegated = facts.delegated ?? snapshot.delegated === true;
57
+ let status;
58
+ if (snapshot.status === 'cancelled')
59
+ status = 'cancelled';
60
+ else if (snapshot.status === 'failed')
61
+ status = 'failed';
62
+ else if (accepted === true)
63
+ status = 'accepted';
64
+ else if (facts.cancellationPhase === 'awaiting_outcome' ||
65
+ facts.takeoverPhase === 'awaiting_outcome')
66
+ status = 'awaiting_outcome';
67
+ else if (facts.cancellationPhase === 'stopping')
68
+ status = 'stopping';
69
+ else if (facts.takeoverPhase === 'stopping')
70
+ status = 'starting';
71
+ else if (facts.superseded === true && snapshot.status !== 'completed')
72
+ status = 'superseded';
73
+ else if ((facts.phase === 'paused' || runnerStatus === 'paused') && snapshot.status !== 'completed')
74
+ status = 'paused';
75
+ // 未消费中断优先于 completed/结果就绪(decideGoalPlan rule 1 已按此给文案),
76
+ // 但持久化终态(cancelled/failed)和真实验收结论先于它。
77
+ else if (interrupted)
78
+ status = 'paused';
79
+ else if (needsUserFacts || runnerStatus === 'waiting_user')
80
+ status = 'waiting_user';
81
+ // 预算/范围耗尽是真的需要人决策(rule 5b 已给 needs_you/decide_blocked):
82
+ // 不能被父代理等待标记等技术阻塞吞掉,也不能让 status 落在 running,
83
+ // 否则同一行会出现「由主 Bot 跟进 / 运行中 + 需要你决定」,真实预算决策丢失。
84
+ // 活流(liveExecution / conversationLive)说明预算门尚未真正落下,交给既有规则。
85
+ else if (runnerStatus === 'budget_exhausted' &&
86
+ !liveExecution &&
87
+ snapshot.conversationLive !== true)
88
+ status = 'waiting_user';
89
+ // 技术阻塞是父代理的工作,不是人类问题;活流说明阻塞已过期。
90
+ // 这里刻意保留 completed 的既有优先级:技术残留不越过完成,也不制造人类门,
91
+ // 只有真实人类门(审批/权限/提问/预算)能越过 completed(见 lifecyclePresentation)。
92
+ else if ((blockedReason === 'waiting_parent_agent' || snapshot.agentWaiting === true) &&
93
+ facts.phase !== 'paused' &&
94
+ facts.superseded !== true &&
95
+ runnerStatus !== 'paused' &&
96
+ !liveExecution)
97
+ status = 'waiting_agent';
98
+ else if (verificationActive)
99
+ status = 'verifying';
100
+ else if (runnerStatus === 'blocked' && !liveExecution)
101
+ status = 'waiting_agent';
102
+ else if (snapshot.status === 'completed' && runnerStatus && ACTIVE_EXECUTION_RUNNER_STATUSES.has(runnerStatus))
103
+ status = 'running';
104
+ // 计划已完成、但本进程仍持有执行 token(可能还没有 runner 状态字符串)。
105
+ else if (snapshot.status === 'completed' && liveExecution)
106
+ status = 'running';
107
+ else if (snapshot.status === 'completed')
108
+ status = 'result_ready';
109
+ else if (facts.phase === 'starting')
110
+ status = 'starting';
111
+ else if (['approved', 'accepted', 'paused', 'interrupted'].includes(snapshot.status) ||
112
+ facts.phase === 'queued')
113
+ status = 'queued';
114
+ else
115
+ status = 'running';
116
+ // 五字段必须同源:状态定稿后由同一个出口给出文案/行动权/下一步/可取消。
117
+ const presentation = lifecyclePresentation(status, decision, {
118
+ delegated,
119
+ accepted: accepted === true,
120
+ takeoverStopping: facts.takeoverPhase === 'stopping',
121
+ budgetGate: runnerStatus === 'budget_exhausted' &&
122
+ !liveExecution &&
123
+ snapshot.conversationLive !== true,
124
+ });
125
+ return {
126
+ ...presentation,
127
+ status,
128
+ cancelable: presentation.actionRight !== 'terminal' && !NON_CANCELABLE_STATUSES.has(status),
129
+ needsUser: status === 'waiting_user',
130
+ verificationActive: status === 'verifying',
131
+ ...(blockedReason ? { blockedReason } : {}),
132
+ };
133
+ }
134
+ /**
135
+ * 状态语义 → 同一行文案/行动权(ADR 102 §4)。
15
136
  *
16
- * 输入设计:投影函数接收最小输入快照(ProjectionSnapshot),而非完整
17
- * GoalPlan / AutomationRun 对象——调用方(main 进程聚合层)负责从
18
- * 存储读出字段后组装快照,renderer 只拿到投影产物。这样契约边界清晰,
19
- * 且测试无需构造巨型 fixture。
137
+ * 只覆盖"旧规则看不到这些事实"的 status;其余沿用既有文案,避免修一个坑挖一个坑。
138
+ * 调用方(任务卡/工作会话/抽屉)必须直接消费 decideLifecycle 的返回值。
20
139
  */
21
- import { projectGoalTiming } from "./goal.js";
140
+ function lifecyclePresentation(status, legacy, facts) {
141
+ switch (status) {
142
+ case 'waiting_user':
143
+ // completed 只说明计划已落库完成,不等于没有待你消费的决策:旧规则表把
144
+ // completed 放在最前(rule 16),会把预算门/待确认门吞成「已完成 / terminal」。
145
+ // 规则表已经给出 needs_you 的(审批、提问、权限、活跃计划预算)原样沿用,
146
+ // 只补它看不到的事实,文案/下一步复用既有配对,不新发明口径。
147
+ if (legacy.actionRight === 'needs_you')
148
+ return legacy;
149
+ return facts.budgetGate
150
+ ? {
151
+ actionRight: 'needs_you',
152
+ needsYouReason: 'decision',
153
+ nextAction: 'decide_blocked',
154
+ statusLabel: '预算已耗尽',
155
+ actionLabel: '决策',
156
+ }
157
+ : {
158
+ actionRight: 'needs_you',
159
+ needsYouReason: 'user_input',
160
+ nextAction: 'answer_question',
161
+ statusLabel: '等待你的选择',
162
+ actionLabel: '回答 →',
163
+ };
164
+ case 'verifying':
165
+ // 核验 ≠ 完成:即使 plan 已落 completed,核验在跑就是核验中。
166
+ return {
167
+ actionRight: 'peer_advancing',
168
+ nextAction: 'none',
169
+ statusLabel: '核验中',
170
+ actionLabel: '查看 →',
171
+ };
172
+ case 'stopping':
173
+ return {
174
+ actionRight: 'peer_advancing',
175
+ nextAction: 'none',
176
+ statusLabel: '正在停止',
177
+ actionLabel: '查看 →',
178
+ };
179
+ case 'awaiting_outcome':
180
+ return {
181
+ actionRight: 'peer_advancing',
182
+ nextAction: 'none',
183
+ statusLabel: '执行结果待核实',
184
+ actionLabel: '查看 →',
185
+ };
186
+ case 'waiting_agent':
187
+ // 技术阻塞是父代理的跟进项,不是人类待办;具体文案(等待答复/系统中断)沿用旧规则。
188
+ return legacy.actionRight === 'needs_you'
189
+ ? {
190
+ actionRight: 'peer_advancing',
191
+ nextAction: 'none',
192
+ statusLabel: '由主 Bot 跟进',
193
+ actionLabel: '查看 →',
194
+ }
195
+ : legacy;
196
+ case 'starting':
197
+ return facts.takeoverStopping
198
+ ? {
199
+ actionRight: 'peer_advancing',
200
+ nextAction: 'none',
201
+ statusLabel: '正在接手',
202
+ actionLabel: '查看 →',
203
+ }
204
+ : legacy;
205
+ case 'result_ready':
206
+ // 委派结果必须等真实验收:完成 ≠ 已验收(ADR 102 O4.2)。
207
+ // 非委派历史数据沿用既有完成契约(rule 6),不强制进入验收卡点。
208
+ return facts.delegated && !facts.accepted
209
+ ? {
210
+ actionRight: 'result_ready',
211
+ nextAction: 'review_result',
212
+ statusLabel: '等待验收',
213
+ actionLabel: '验收 →',
214
+ }
215
+ : legacy;
216
+ default:
217
+ return legacy;
218
+ }
219
+ }
22
220
  /** Conversation → 无计划讨论态(工作台动线 §15)。 */
23
221
  /**
24
222
  * 会话是否对首页「正在讨论」可见(未读)。
@@ -93,7 +291,7 @@ export function projectConversation(snapshot) {
93
291
  * 因此实现时将 rule 14 放在 rule 8 之后、仅当 runner 显式 idle 时生效。
94
292
  */
95
293
  export function projectGoalPlan(snapshot, options) {
96
- const decision = decideGoalPlan(snapshot);
294
+ const decision = decideLifecycle(snapshot);
97
295
  const projectedTiming = projectGoalTiming(snapshot.timing, options?.nowMs);
98
296
  const durationMs = typeof projectedTiming?.activeMs === 'number' && Number.isFinite(projectedTiming.activeMs)
99
297
  ? Math.max(0, Math.floor(projectedTiming.activeMs))
@@ -170,6 +368,7 @@ export function projectGoalPlan(snapshot, options) {
170
368
  : {}),
171
369
  ...(modelLabel ? { modelLabel } : {}),
172
370
  ...(providerLabel ? { providerLabel } : {}),
371
+ cancelable: decision.cancelable,
173
372
  actionLabel: decision.actionLabel,
174
373
  ...(snapshot.conversationId ? { conversationId: snapshot.conversationId } : {}),
175
374
  };
@@ -234,6 +433,15 @@ function decideGoalPlan(snapshot) {
234
433
  };
235
434
  }
236
435
  }
436
+ // 计划已完成但本进程仍持有真实执行 token:不得投影为终态/已完成。
437
+ if (snapshot.liveExecution === true) {
438
+ return {
439
+ actionRight: 'peer_advancing',
440
+ nextAction: 'none',
441
+ statusLabel: 'Peer 正在推进',
442
+ actionLabel: '查看 →',
443
+ };
444
+ }
237
445
  return {
238
446
  actionRight: 'terminal',
239
447
  nextAction: 'none',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/protocol",
3
- "version": "0.1.0-rc.23",
3
+ "version": "0.1.0-rc.25",
4
4
  "description": "Shared host-neutral protocol contracts for Peer Agent runtimes and clients.",
5
5
  "type": "module",
6
6
  "license": "MIT",