@peer-agent/protocol 0.1.0-rc.2 → 0.1.0-rc.21

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.
@@ -1,4 +1,4 @@
1
- import type { GoalCriterionResult, GoalManualConfirmation, GoalSuccessCriterion } from './goal.ts';
1
+ import type { GoalCriterionResult, GoalManualConfirmation, GoalSuccessCriterion, GoalModelReview } from './goal.ts';
2
2
  export declare const ACCEPTANCE_CLOSE_GATE_CODE = "acceptance_evidence_incomplete";
3
3
  export type AcceptanceCloseGapReason = 'missing' | 'failed' | 'unresolved';
4
4
  export interface AcceptanceCloseGap {
@@ -17,6 +17,15 @@ export interface AcceptanceCloseTaskLike {
17
17
  }
18
18
  export interface AcceptanceClosePlanLike {
19
19
  readonly successCriteria?: readonly GoalSuccessCriterion[] | null;
20
+ /** Current content revision derived by the host store, never admitted from a model patch. */
21
+ readonly modelReviewSourceRevision?: string;
22
+ readonly modelReviews?: readonly GoalModelReview[];
23
+ readonly runner?: {
24
+ readonly verifierRuns?: readonly {
25
+ readonly verifierRunId: string;
26
+ readonly status: string;
27
+ }[];
28
+ };
20
29
  readonly criterionResults?: readonly GoalCriterionResult[] | null;
21
30
  readonly manualConfirmations?: readonly GoalManualConfirmation[] | null;
22
31
  readonly evidenceRefs?: readonly string[] | null;
@@ -85,6 +85,18 @@ export function evaluateAcceptanceCloseGate(plan, options = {}) {
85
85
  const description = criterion.description?.trim() || id;
86
86
  const isAuto = AUTO_CRITERION_KINDS.has(criterion.kind);
87
87
  const result = results.get(id) ?? null;
88
+ if (criterion.kind === 'model_review') {
89
+ const review = plan?.modelReviews?.slice().reverse().find(row => row.criterionId === id);
90
+ const current = review && plan?.modelReviewSourceRevision && review.sourceRevision === plan.modelReviewSourceRevision;
91
+ const verified = current && plan?.runner?.verifierRuns?.some(run => run.verifierRunId === review.verifierRunId && run.status === 'passed');
92
+ if (!current || !verified)
93
+ gaps.push({ criterionId: id, description, reason: 'missing' });
94
+ else if (!review.passed)
95
+ gaps.push({ criterionId: id, description, reason: 'failed' });
96
+ else if (!review.evidenceRefs.length || !review.evidenceRefs.every(ref => known.has(ref)))
97
+ gaps.push({ criterionId: id, description, reason: 'unresolved' });
98
+ continue;
99
+ }
88
100
  if (!isAuto && latestManualApproval(plan ?? {}, id))
89
101
  continue;
90
102
  if (!result) {
@@ -0,0 +1,13 @@
1
+ import type { BotProfile } from './project.ts';
2
+ import type { ModelReasoningEffort } from './model-reasoning.ts';
3
+ /** A user choice for the Bot's future replies; never a per-input runtime override. */
4
+ export interface BotModelSelectionUpdateRequest {
5
+ readonly workspaceId: string;
6
+ readonly modelProviderId: string;
7
+ readonly reasoningEffort?: ModelReasoningEffort;
8
+ }
9
+ export interface BotModelSelectionUpdateResult {
10
+ readonly ok: boolean;
11
+ readonly code?: string;
12
+ readonly profile?: BotProfile;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,68 @@
1
+ /** Coordination authority is issued by the local host, never by model arguments. */
2
+ export type CoordinationAction = 'parallel' | 'augment' | 'revise' | 'query' | 'answer' | 'cancel' | 'replace' | 'handoff';
3
+ export type CoordinationLifecycle = 'active' | 'paused' | 'cancelled' | 'fulfilled';
4
+ export interface CoordinationMandate {
5
+ schemaVersion: 1;
6
+ mandateId: string;
7
+ workId: string;
8
+ workspaceId: string;
9
+ parentConversationId: string;
10
+ rootInputIds: string[];
11
+ revisionInputIds: string[];
12
+ goalRevision: number;
13
+ allowedActions: CoordinationAction[];
14
+ sessionIds: string[];
15
+ revokedSessionIds?: string[];
16
+ executionBindings?: Record<string, CoordinationExecutionBinding>;
17
+ materialRefs: string[];
18
+ policyRevision: string;
19
+ lifecycle: CoordinationLifecycle;
20
+ }
21
+ /** Semantic routing is the model's decision; identity, authority and versions are host facts. */
22
+ export interface CoordinationDecision {
23
+ operationId: string;
24
+ workId: string;
25
+ expectedRevision: number;
26
+ action: CoordinationAction;
27
+ sourceInputIds: string[];
28
+ sourceEventIds: string[];
29
+ sessionId?: string;
30
+ reason: string;
31
+ }
32
+ export type TaskTransitionPhase = 'recorded' | 'stopping' | 'awaiting_outcome' | 'ready' | 'started' | 'completed' | 'blocked';
33
+ export interface TaskTransition {
34
+ schemaVersion: 1;
35
+ operationId: string;
36
+ workId: string;
37
+ mandateId: string;
38
+ expectedGoalRevision: number;
39
+ sourceInputIds: string[];
40
+ sourceEventIds: string[];
41
+ initiator: 'project_agent';
42
+ decisionSource: 'user_revision' | 'execution_repair';
43
+ action: CoordinationAction;
44
+ reason: string;
45
+ oldSessionId?: string;
46
+ replacementSessionId?: string;
47
+ executionEpoch: string;
48
+ phase: TaskTransitionPhase;
49
+ minimumExecutorVersion: 1;
50
+ updatedAt: string;
51
+ }
52
+ export interface CoordinationExecutionBinding {
53
+ sessionId?: string;
54
+ workId: string;
55
+ goalRevision: number;
56
+ executionEpoch: string;
57
+ }
58
+ /** Factual view of a durable operation; completed means disposition applied, not task success. */
59
+ export interface CoordinationSessionFacts {
60
+ readonly operationId: string;
61
+ readonly action: CoordinationAction;
62
+ readonly phase: TaskTransitionPhase;
63
+ readonly reason: string;
64
+ readonly goalRevision: number;
65
+ readonly priorSessionId?: string;
66
+ readonly replacementSessionId?: string;
67
+ readonly replacementTitle?: string;
68
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -4,10 +4,28 @@
4
4
  */
5
5
  import type { ModelSelectionSnapshot } from './model-routing.ts';
6
6
  import { type GoalPlanProjectionSnapshot, type TaskOverviewItem } from './task-overview.ts';
7
- export type WorkSessionStatus = 'paused' | 'queued' | 'starting' | 'running' | 'waiting_user' | 'verifying' | 'result_ready' | 'accepted' | 'failed' | 'cancelled' | 'superseded';
8
- export declare const WORK_SESSION_STATUSES: readonly ["paused", "queued", "starting", "running", "waiting_user", "verifying", "result_ready", "accepted", "failed", "cancelled", "superseded"];
7
+ export type WorkSessionStatus = 'paused' | 'queued' | 'starting' | 'running' | 'waiting_user' | 'waiting_agent' | 'stopping' | 'awaiting_outcome' | 'verifying' | 'result_ready' | 'accepted' | 'failed' | 'cancelled' | 'superseded';
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';
10
10
  export interface DelegationOrigin {
11
+ readonly takeover?: {
12
+ operationId: string;
13
+ phase: 'stopping' | 'completed';
14
+ text: string;
15
+ binding: import('./delegation-coordination.ts').CoordinationExecutionBinding;
16
+ requestedAt: string;
17
+ completedAt?: string;
18
+ };
19
+ readonly coordinationBinding?: import('./delegation-coordination.ts').CoordinationExecutionBinding;
20
+ readonly cancellation?: {
21
+ readonly operationId: string;
22
+ readonly reason: string;
23
+ readonly phase: 'stopping' | 'awaiting_outcome' | 'completed';
24
+ readonly requestedAt: string;
25
+ readonly completedAt?: string;
26
+ readonly evidenceCalls?: readonly string[];
27
+ };
28
+ readonly workId?: string;
11
29
  readonly anchorMessageId: string;
12
30
  readonly inputId: string;
13
31
  readonly surface: InputSurface;
@@ -35,6 +53,7 @@ export interface SessionQueueFacts {
35
53
  readonly queueReason?: 'dependencies' | 'dependency_missing' | 'dependency_failed' | 'read_slot' | 'write_slot' | 'disk_space' | 'isolation_failed' | null;
36
54
  }
37
55
  export interface WorkSessionConversationMeta extends SessionQueueFacts {
56
+ readonly coordination?: import('./delegation-coordination.ts').CoordinationSessionFacts;
38
57
  readonly sessionId?: string;
39
58
  readonly conversationId?: string;
40
59
  readonly workspaceId: string;
@@ -47,6 +66,7 @@ export interface WorkSessionConversationMeta extends SessionQueueFacts {
47
66
  readonly phase?: 'starting' | 'verifying' | 'paused';
48
67
  }
49
68
  export interface WorkSession extends SessionQueueFacts {
69
+ readonly coordination?: import('./delegation-coordination.ts').CoordinationSessionFacts;
50
70
  readonly sessionId: string;
51
71
  readonly workspaceId: string;
52
72
  readonly title: string;
@@ -66,14 +86,41 @@ export interface SessionReport {
66
86
  readonly planId: string | null;
67
87
  readonly status: WorkSessionStatus;
68
88
  readonly summary: string;
89
+ readonly taskBrief?: string;
69
90
  readonly keyFindings: readonly string[];
70
91
  readonly changedFiles: readonly {
71
92
  readonly path: string;
72
93
  readonly summary: string;
73
94
  }[];
74
95
  readonly evidenceRefs: readonly string[];
96
+ /** Persisted worker output is a claim; verification still comes from host Evidence. */
97
+ readonly contentSource?: {
98
+ readonly kind: 'worker_message' | 'task_results';
99
+ readonly conversationId?: string;
100
+ readonly messageId?: string;
101
+ readonly verification: 'unverified';
102
+ };
103
+ }
104
+ export type DelegationEventKind = 'agent_message' | 'session_running' | 'session_spawned' | 'session_progress' | 'session_needs_user' | 'report_available' | 'session_verified' | 'session_ended' | 'user_intervened' | 'objective_signal' | 'digest_due';
105
+ /** Local orchestration facts; never a human authorization or a verified result. */
106
+ export interface AgentMessage {
107
+ readonly replyTo?: string;
108
+ readonly messageId: string;
109
+ readonly workspaceId: string;
110
+ readonly sessionId: string;
111
+ readonly senderConversationId: string;
112
+ readonly recipientConversationId: string;
113
+ readonly direction: 'parent_to_child' | 'child_to_parent';
114
+ readonly purpose: 'update' | 'question' | 'answer';
115
+ readonly text: string;
116
+ readonly at: string;
117
+ }
118
+ export interface AgentActivity {
119
+ readonly eventId: string;
120
+ readonly sessionId: string;
121
+ readonly name: string;
122
+ readonly state: 'queued' | 'started' | 'update' | 'question' | 'answer' | 'reported' | 'verified' | 'ended' | 'cancelled' | 'blocked';
75
123
  }
76
- export type DelegationEventKind = 'session_spawned' | 'session_progress' | 'session_needs_user' | 'session_verified' | 'session_ended' | 'user_intervened' | 'objective_signal' | 'digest_due';
77
124
  export type JsonValue = null | string | number | boolean | readonly JsonValue[] | {
78
125
  readonly [key: string]: JsonValue;
79
126
  };
@@ -101,6 +148,9 @@ export interface AgentReplyMeta {
101
148
  readonly surfacing: 'interrupt' | 'message' | 'digest' | 'silent';
102
149
  }
103
150
  export interface ReplySessionState {
151
+ readonly sourceRevision?: string;
152
+ /** Stable reporting facts, including a changed verifier failure; not acceptance authority. */
153
+ readonly observationRevision?: string;
104
154
  readonly sessionId: string;
105
155
  readonly status: WorkSessionStatus;
106
156
  }
@@ -155,6 +205,26 @@ export interface DispositionEvent {
155
205
  readonly replyMessageId?: string;
156
206
  }
157
207
  export type VerificationOutcome = 'passed' | 'failed' | 'partial' | 'unverifiable';
208
+ /** Host-bound manual completion review; distinct from acceptance of a completed result. */
209
+ export interface SessionCompletionReview {
210
+ readonly sessionId: string;
211
+ readonly reviewToken: string;
212
+ readonly criteria: readonly {
213
+ readonly id: string;
214
+ readonly description: string;
215
+ }[];
216
+ readonly report: string;
217
+ readonly confirmed?: boolean;
218
+ }
219
+ export type SessionConfirmationInput = {
220
+ readonly workspaceId: string;
221
+ readonly sessionId: string;
222
+ } & ({
223
+ readonly stage?: 'result_acceptance';
224
+ } | {
225
+ readonly stage: 'manual_completion';
226
+ readonly reviewToken: string;
227
+ });
158
228
  export type IndependentVerifierState = 'passed' | 'failed' | 'not_required' | 'missing';
159
229
  export interface VerificationCheck {
160
230
  readonly name: string;
@@ -200,6 +270,22 @@ export interface SurfacingEvent {
200
270
  readonly severity: 'info' | 'notable' | 'urgent';
201
271
  readonly deadlineImminent?: boolean;
202
272
  }
273
+ /** Explicit user uploads are factual user context, never execution authority. */
274
+ export type ProjectInputAttachment = {
275
+ readonly id: string;
276
+ readonly name: string;
277
+ readonly mimeType: string;
278
+ readonly size: number;
279
+ readonly sourceKind: 'user_upload';
280
+ } & ({
281
+ readonly kind: 'image';
282
+ readonly dataUrl: string;
283
+ } | {
284
+ readonly kind: 'text';
285
+ readonly text: string;
286
+ } | {
287
+ readonly kind: 'unsupported';
288
+ });
203
289
  export interface ProjectInput {
204
290
  readonly inputId: string;
205
291
  readonly workspaceId: string;
@@ -208,10 +294,13 @@ export interface ProjectInput {
208
294
  readonly anchorRefs: readonly string[];
209
295
  readonly quoteRefs: readonly string[];
210
296
  readonly attachmentRefs: readonly string[];
297
+ readonly attachments?: readonly ProjectInputAttachment[];
211
298
  readonly createdAt: string;
212
299
  }
213
- export type PendingApprovalState = 'open' | 'approved' | 'denied' | 'expired' | 'stale';
300
+ export type PendingApprovalState = 'open' | 'approved' | 'denied' | 'expired' | 'stale' | 'cancelled';
214
301
  export interface PendingApproval {
302
+ readonly imageReadScope?: import('./local-image.ts').LocalImagePermissionScope;
303
+ readonly imageReadGrant?: import('./local-image.ts').ImageReadGrant;
215
304
  readonly approvalId: string;
216
305
  readonly workspaceId: string | null;
217
306
  readonly sessionId?: string | null;
@@ -225,6 +314,8 @@ export interface PendingApproval {
225
314
  readonly argsDigest: string;
226
315
  readonly createdAt: string;
227
316
  readonly state: PendingApprovalState;
317
+ readonly deadlineAt?: string;
318
+ readonly decisionReason?: 'permission_cancelled' | 'permission_timeout' | 'permission_unavailable' | 'local_user_denied';
228
319
  readonly decidedAt?: string;
229
320
  readonly decidedBy?: 'local_ui' | 'policy';
230
321
  }
@@ -1,9 +1,6 @@
1
- /**
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.
4
- */
1
+ import { deriveSessionFacts } from "./session-facts.js";
5
2
  import { projectGoalPlan, } from "./task-overview.js";
6
- export const WORK_SESSION_STATUSES = ['paused', 'queued', 'starting', 'running', 'waiting_user', 'verifying',
3
+ export const WORK_SESSION_STATUSES = ['paused', 'queued', 'starting', 'running', 'waiting_user', 'waiting_agent', 'stopping', 'awaiting_outcome', 'verifying',
7
4
  'result_ready', 'accepted', 'failed', 'cancelled', 'superseded'];
8
5
  function fnv1a(text) {
9
6
  let hash = 0x811c9dc5;
@@ -44,38 +41,15 @@ export function createDelegationEvent(input) {
44
41
  };
45
42
  }
46
43
  function delegationStatus(snapshot, meta, projected) {
47
- if (snapshot.status === 'failed')
48
- return 'failed';
49
- if (snapshot.status === 'cancelled')
50
- return 'cancelled';
51
- if (snapshot.status === 'completed') {
52
- if (meta.verifying || meta.phase === 'verifying')
53
- return 'verifying';
54
- if (meta.acceptance === 'confirm' && meta.accepted !== true)
55
- return 'result_ready';
56
- return 'accepted';
57
- }
58
- if (meta.supersededBy)
59
- return 'superseded';
60
- if (meta.phase === 'paused')
61
- return 'paused';
62
- // 复核进行中盖过「需要你」。草稿、待批准、等回答的计划在独立复核时都显示 verifying。
63
- if (meta.verifying || meta.phase === 'verifying')
64
- return 'verifying';
65
- if (projected.actionRight === 'needs_you')
66
- return 'waiting_user';
67
- if (snapshot.runnerStatus === 'exploring')
68
- return 'verifying';
69
- if (meta.phase === 'starting')
70
- return 'starting';
71
- if (snapshot.status === 'approved'
72
- || snapshot.status === 'accepted'
73
- || snapshot.status === 'paused'
74
- || snapshot.status === 'interrupted'
75
- || projected.actionRight === 'paused') {
76
- return 'queued';
77
- }
78
- return 'running';
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;
79
53
  }
80
54
  /**
81
55
  * Project a GoalPlan snapshot into a work session.
@@ -84,16 +58,22 @@ function delegationStatus(snapshot, meta, projected) {
84
58
  */
85
59
  export function projectWorkSession(plan, conversationMeta) {
86
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';
87
64
  return {
88
65
  sessionId: conversationMeta.sessionId ?? plan.conversationId ?? plan.planId,
89
66
  workspaceId: conversationMeta.workspaceId,
90
67
  title: plan.title,
91
68
  planId: plan.planId,
92
- status: delegationStatus(plan, conversationMeta, projected),
93
- actionRight: projected.actionRight,
94
- nextAction: projected.nextAction,
95
- statusLabel: projected.statusLabel,
96
- ...(projected.needsYouReason ? { needsYouReason: projected.needsYouReason } : {}),
69
+ 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 } : {}),
76
+ ...(conversationMeta.coordination ? { coordination: conversationMeta.coordination } : {}),
97
77
  spawnedAt: conversationMeta.spawnedAt ?? plan.updatedAt ?? '',
98
78
  ...(conversationMeta.conversationId ? { conversationId: conversationMeta.conversationId } : {}),
99
79
  origin: conversationMeta.origin,
@@ -0,0 +1,22 @@
1
+ /** Read-only display facts. A saved operation is not proof that its task completed. */
2
+ export interface EvidenceSourceDescription {
3
+ readonly evidenceRef: string;
4
+ readonly toolName?: string;
5
+ readonly createdAt?: string;
6
+ }
7
+ export interface ProjectAgentEvidenceReadRequest {
8
+ readonly evidenceRef?: string;
9
+ /** Source descriptions only; at most 100 unique references, no body or artifact reads. */
10
+ readonly evidenceRefs?: readonly string[];
11
+ }
12
+ export interface ProjectAgentEvidenceReadResult {
13
+ readonly ok: boolean;
14
+ readonly code?: string;
15
+ readonly evidenceRef?: string;
16
+ readonly kind?: 'file' | 'command' | 'diff' | 'screenshot' | 'observation';
17
+ readonly summary?: string;
18
+ readonly truncated?: boolean;
19
+ readonly availability?: 'available' | 'metadata_only' | 'not_found' | 'unavailable';
20
+ readonly source?: EvidenceSourceDescription;
21
+ readonly items?: readonly EvidenceSourceDescription[];
22
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/goal.d.ts CHANGED
@@ -444,7 +444,7 @@ export interface GoalRunTrace {
444
444
  readonly lastCheckpointNodeId?: string;
445
445
  readonly events: readonly GoalRunEvent[];
446
446
  }
447
- export type GoalSuccessCriterionKind = 'command' | 'test' | 'file-contains' | 'file-exists' | 'manual';
447
+ export type GoalSuccessCriterionKind = 'command' | 'test' | 'file-contains' | 'file-exists' | 'model_review' | 'manual';
448
448
  export interface GoalSuccessCriterion {
449
449
  readonly id: string;
450
450
  readonly kind: GoalSuccessCriterionKind;
@@ -452,6 +452,21 @@ export interface GoalSuccessCriterion {
452
452
  readonly command?: string;
453
453
  readonly path?: string;
454
454
  readonly expect?: string;
455
+ readonly authority?: {
456
+ readonly source: 'model' | 'user' | 'project_policy' | 'legacy_unknown';
457
+ readonly sourceRef?: string;
458
+ readonly version: number;
459
+ readonly verifier: 'mechanical' | 'host_model' | 'human';
460
+ readonly rationale: string;
461
+ };
462
+ }
463
+ export interface GoalModelReview {
464
+ readonly criterionId: string;
465
+ readonly sourceRevision: string;
466
+ readonly verifierRunId: string;
467
+ readonly passed: boolean;
468
+ readonly evidenceRefs: readonly string[];
469
+ readonly checkedAt: string;
455
470
  }
456
471
  export interface GoalCriterionResult {
457
472
  readonly criterionId: string;
@@ -567,6 +582,28 @@ export interface GoalExecutionCheckpoint {
567
582
  }
568
583
  /** GoalPlan 内嵌的轻量 runner 状态;不代表工具执行事实,任务完成仍必须由 Evidence 回写。 */
569
584
  export interface GoalRunnerState {
585
+ /** Host-owned readonly review continuity. Native messages stay in registered checkpoint storage. */
586
+ readonly verificationContinuation?: {
587
+ readonly schemaVersion: 1;
588
+ readonly policyVersion?: 2;
589
+ readonly planId: string;
590
+ readonly continuationId: string;
591
+ readonly sourceRevision: string;
592
+ readonly modelKey: string;
593
+ readonly workId?: string;
594
+ readonly phase: 'ready' | 'requesting' | 'tools' | 'completed';
595
+ /** Current slice deadline; legacy review-wide deadlines are renewed only on safe admission. */
596
+ readonly deadlineAt: string;
597
+ readonly modelRequests: number;
598
+ readonly toolCalls: number;
599
+ readonly formatAttempt: number;
600
+ readonly previousText?: string;
601
+ readonly checkpointRef?: string;
602
+ readonly evidenceRefs: readonly string[];
603
+ readonly fingerprint?: string;
604
+ readonly repeats?: number;
605
+ readonly progressFacts?: readonly string[];
606
+ };
570
607
  readonly enabled: boolean;
571
608
  readonly status: GoalRunnerStatus;
572
609
  readonly intent?: GoalRunnerIntent;
@@ -678,6 +715,9 @@ export interface GoalPlan {
678
715
  readonly successCriteria: readonly GoalSuccessCriterion[];
679
716
  readonly criterionResults: readonly GoalCriterionResult[];
680
717
  readonly manualConfirmations?: readonly GoalManualConfirmation[];
718
+ readonly modelReviews?: readonly GoalModelReview[];
719
+ /** Host-derived current revision for checking semantic review freshness. */
720
+ readonly modelReviewSourceRevision?: string;
681
721
  readonly boundaries: GoalBoundaries;
682
722
  readonly exceptionPolicies: ExceptionPolicy[];
683
723
  /** 顶层汇总(来源于子任务) */
package/dist/index.d.ts CHANGED
@@ -1,3 +1,10 @@
1
+ export type { ProjectWorkBudgetLimits, ProjectWorkBudgetBoundary, ProjectReplyRecoveryAction, ProjectWorkReceipt, ProjectWorkRecovery, ProjectWorkState, ProjectTurnEnd, ProjectReplyFailureStatus, ProjectAgentSilentWait } from './work-coordination.ts';
2
+ export type { CoordinationAction, CoordinationLifecycle, CoordinationMandate, CoordinationDecision, TaskTransitionPhase, TaskTransition, CoordinationExecutionBinding, CoordinationSessionFacts } from './delegation-coordination.ts';
3
+ export { deriveSessionFacts, type SessionFactSnapshot } from './session-facts.ts';
4
+ export { projectAgentFailureKind, classifyProjectAgentFailure, type ProjectRecoveryFailureKind, type ProviderRequestRecovery, type ProjectAgentTurnRecovery, type ReplyAnchorCandidate } from './project-agent-failure.ts';
5
+ export type { EvidenceSourceDescription, ProjectAgentEvidenceReadRequest, ProjectAgentEvidenceReadResult } from './evidence-inspection.ts';
6
+ export { toolActivityPreview, toolActivitySummary } from './tool-activity-preview.ts';
7
+ export { isModelReasoningEffort, modelReasoningLevels, modelDefaultReasoningEffort, type ModelReasoningEffort } from './model-reasoning.ts';
1
8
  export type { SelectionRange, SelectionReference, SelectionDraft, SelectionOrigin, SelectionChildSession, SelectionChildSummary, SelectionChildrenPage, SelectionChildRead } from './selection-reference.ts';
2
9
  export { buildModelMenuGroups, modelMenuChannelName, type ModelMenuRow } from './model-menu.ts';
3
10
  export { evaluateUiDelivery } from './ui-delivery-verification.ts';
@@ -718,6 +725,18 @@ export interface ClientToolCall extends RuntimeToolCall {
718
725
  readonly dataLevel: DataLevel;
719
726
  readonly requestedAt: string;
720
727
  }
728
+ /** Host permission wait events. Requests are presentation, never permission truth. */
729
+ export interface ChatPermissionRequest {
730
+ readonly streamId: string;
731
+ readonly call: ClientToolCall;
732
+ readonly deadlineAt?: string;
733
+ }
734
+ export interface ChatPermissionSettled {
735
+ readonly streamId: string;
736
+ readonly toolCallIds: readonly string[];
737
+ readonly granted?: boolean;
738
+ readonly reason?: string;
739
+ }
721
740
  export interface ClientToolCallPollRequest {
722
741
  readonly sessionId: string;
723
742
  readonly projectionId?: string;
@@ -737,7 +756,7 @@ export interface PermissionGrant {
737
756
  readonly toolCallId: string;
738
757
  readonly granted: boolean;
739
758
  readonly duration: PermissionDuration;
740
- readonly scope?: string;
759
+ readonly scope?: string | import('./local-image.ts').LocalImagePermissionScope;
741
760
  readonly decidedAt: string;
742
761
  }
743
762
  /** Application-owned shell process snapshot. Source conversation is provenance, not ownership. */
@@ -870,3 +889,5 @@ export * from './model-routing.ts';
870
889
  export * from './project.ts';
871
890
  export * from './objectives.ts';
872
891
  export * from './remote-access-settings.ts';
892
+ export type { BotModelSelectionUpdateRequest, BotModelSelectionUpdateResult } from './bot-model-selection.ts';
893
+ export * from './local-image.ts';
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
+ export { deriveSessionFacts } from "./session-facts.js";
2
+ export { projectAgentFailureKind, classifyProjectAgentFailure } from "./project-agent-failure.js";
3
+ export { toolActivityPreview, toolActivitySummary } from "./tool-activity-preview.js";
4
+ export { isModelReasoningEffort, modelReasoningLevels, modelDefaultReasoningEffort } from "./model-reasoning.js";
1
5
  export { buildModelMenuGroups, modelMenuChannelName } from "./model-menu.js";
2
6
  export { evaluateUiDelivery } from "./ui-delivery-verification.js";
3
7
  export { DESKTOP_PREVIEW_PROTOCOL, DESKTOP_PREVIEW_CAPABILITY, DESKTOP_PREVIEW_TOOL } from "./desktop-preview.js";
@@ -37,3 +41,4 @@ export * from "./model-routing.js";
37
41
  export * from "./project.js";
38
42
  export * from "./objectives.js";
39
43
  export * from "./remote-access-settings.js";
44
+ export * from "./local-image.js";
@@ -0,0 +1,52 @@
1
+ /** ADR 90: local images are factual context, never instructions or persisted pixels. */
2
+ export declare const LOCAL_IMAGE_CAPABILITY: "local.image.read";
3
+ export declare const LOCAL_IMAGE_TOOL: "view_image";
4
+ export declare const LOCAL_IMAGE_MAX_BYTES: number;
5
+ export declare const LOCAL_IMAGE_MAX_PIXELS = 24000000;
6
+ export type LocalImageMediaType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp';
7
+ export interface LocalImageMetadata {
8
+ path: string;
9
+ mediaType: LocalImageMediaType;
10
+ width: number;
11
+ height: number;
12
+ byteLength: number;
13
+ sha256: string;
14
+ artifactRef: string;
15
+ }
16
+ /** Ephemeral host sideband. Object identity must also be validated by its Provider. */
17
+ export interface LocalImageObservation extends LocalImageMetadata {
18
+ kind: 'local_image';
19
+ dataUrl: string;
20
+ }
21
+ import type { ClientToolResult, PermissionGrant } from './index.ts';
22
+ export interface LocalImagePermissionScope {
23
+ capabilityId: typeof LOCAL_IMAGE_CAPABILITY;
24
+ path: string;
25
+ workspacePath: string | null;
26
+ action: 'read_image_for_model';
27
+ fileIdentity?: {
28
+ dev: number;
29
+ ino: number;
30
+ size: number;
31
+ mtimeMs: number;
32
+ ctimeMs: number;
33
+ };
34
+ }
35
+ /** Local host-issued exact-image read authority; no pixels are persisted. */
36
+ export interface ImageReadGrant {
37
+ schemaVersion: 1;
38
+ grantId: string;
39
+ workspaceId: string | null;
40
+ conversationId: string;
41
+ expiresAt: number;
42
+ scope: LocalImagePermissionScope;
43
+ }
44
+ /** Concrete image grant; legacy grant scopes remain unchanged. */
45
+ export interface LocalImagePermissionGrant extends PermissionGrant {
46
+ scope: LocalImagePermissionScope | typeof LOCAL_IMAGE_CAPABILITY;
47
+ }
48
+ export interface LocalImageToolResult extends ClientToolResult {
49
+ modelContext?: {
50
+ visualObservations: readonly LocalImageObservation[];
51
+ };
52
+ }
@@ -0,0 +1,5 @@
1
+ /** ADR 90: local images are factual context, never instructions or persisted pixels. */
2
+ export const LOCAL_IMAGE_CAPABILITY = 'local.image.read';
3
+ export const LOCAL_IMAGE_TOOL = 'view_image';
4
+ export const LOCAL_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
5
+ export const LOCAL_IMAGE_MAX_PIXELS = 24_000_000;
@@ -0,0 +1,13 @@
1
+ /** Provider-declared effort values. Unknown capabilities do not create UI choices. */
2
+ export type ModelReasoningEffort = 'off' | 'low' | 'medium' | 'default' | 'high' | 'xhigh' | 'max';
3
+ export declare function isModelReasoningEffort(value: unknown): value is ModelReasoningEffort;
4
+ export declare function modelReasoningLevels(provider: {
5
+ readonly supportsReasoning?: unknown;
6
+ readonly reasoningEffortLevels?: unknown;
7
+ }): readonly ModelReasoningEffort[];
8
+ export declare function modelDefaultReasoningEffort(provider: {
9
+ readonly supportsReasoning?: unknown;
10
+ readonly reasoningEffortLevels?: unknown;
11
+ readonly reasoningEffort?: unknown;
12
+ readonly defaultEffort?: unknown;
13
+ }): ModelReasoningEffort | undefined;
@@ -0,0 +1,18 @@
1
+ const ORDER = ['off', 'low', 'medium', 'default', 'high', 'xhigh', 'max'];
2
+ export function isModelReasoningEffort(value) {
3
+ return ORDER.includes(value);
4
+ }
5
+ export function modelReasoningLevels(provider) {
6
+ if (provider.supportsReasoning === false || !Array.isArray(provider.reasoningEffortLevels))
7
+ return [];
8
+ const declared = provider.reasoningEffortLevels;
9
+ return ORDER.filter(value => declared.includes(value));
10
+ }
11
+ export function modelDefaultReasoningEffort(provider) {
12
+ const levels = modelReasoningLevels(provider);
13
+ for (const value of [provider.reasoningEffort, provider.defaultEffort, 'default', 'medium', 'high', 'low', ...levels]) {
14
+ if (isModelReasoningEffort(value) && levels.includes(value))
15
+ return value;
16
+ }
17
+ return undefined;
18
+ }
@@ -1,3 +1,4 @@
1
+ import { type ModelReasoningEffort } from './model-reasoning.ts';
1
2
  /**
2
3
  * Role and tier model routing. Resolution is pure; hosts apply the result.
3
4
  * Order and filters follow ADR 83. An empty candidate set is an error, not a silent downgrade.
@@ -10,6 +11,7 @@ export type RoleSetting = {
10
11
  } | {
11
12
  readonly mode: 'fixed';
12
13
  readonly modelProviderId: string;
14
+ readonly reasoningEffort?: ModelReasoningEffort;
13
15
  } | {
14
16
  readonly mode: 'auto';
15
17
  readonly pool: readonly string[];
@@ -65,7 +67,15 @@ export interface ModelRoutingMenuOption {
65
67
  readonly supportsTools: boolean;
66
68
  readonly supportsStructured: boolean;
67
69
  readonly contextTokens: number;
70
+ readonly available?: boolean;
71
+ readonly reasoningEffortLevels?: readonly ModelReasoningEffort[];
72
+ readonly defaultReasoningEffort?: ModelReasoningEffort;
68
73
  }
74
+ export interface BotRoleModelView {
75
+ readonly resolution: ModelResolution;
76
+ readonly eligibleModelIds: readonly string[];
77
+ }
78
+ export type BotModelViews = Partial<Record<ModelRole, BotRoleModelView>>;
69
79
  /** Project one configured provider into the routing menu contract. */
70
80
  export declare function projectModelRoutingMenuOption(provider: {
71
81
  readonly id?: unknown;
@@ -81,6 +91,12 @@ export declare function projectModelRoutingMenuOption(provider: {
81
91
  readonly toolUse?: unknown;
82
92
  } | null;
83
93
  readonly contextWindow?: unknown;
94
+ readonly apiKeyConfigured?: unknown;
95
+ readonly enabled?: unknown;
96
+ readonly supportsReasoning?: unknown;
97
+ readonly reasoningEffortLevels?: unknown;
98
+ readonly reasoningEffort?: unknown;
99
+ readonly defaultEffort?: unknown;
84
100
  } | null | undefined): ModelRoutingMenuOption | null;
85
101
  export interface CatalogModel {
86
102
  readonly modelProviderId: string;
@@ -93,6 +109,7 @@ export interface CatalogModel {
93
109
  readonly contextTokens?: number;
94
110
  readonly local?: boolean;
95
111
  readonly reasoningEffort?: string;
112
+ readonly reasoningEffortLevels?: readonly ModelReasoningEffort[];
96
113
  }
97
114
  export type ModelResolution = {
98
115
  readonly ok: true;
@@ -101,7 +118,7 @@ export type ModelResolution = {
101
118
  readonly sameFamilyAsWorker?: boolean;
102
119
  } | {
103
120
  readonly ok: false;
104
- readonly reason: 'capability' | 'scope' | 'auto_pool' | 'empty';
121
+ readonly reason: 'capability' | 'scope' | 'auto_pool' | 'empty' | 'reasoning';
105
122
  readonly missing: string;
106
123
  };
107
124
  export interface RoleModelRequest {
@@ -1,7 +1,4 @@
1
- /**
2
- * Role and tier model routing. Resolution is pure; hosts apply the result.
3
- * Order and filters follow ADR 83. An empty candidate set is an error, not a silent downgrade.
4
- */
1
+ import { modelDefaultReasoningEffort, modelReasoningLevels } from "./model-reasoning.js";
5
2
  /** Project one configured provider into the routing menu contract. */
6
3
  export function projectModelRoutingMenuOption(provider) {
7
4
  if (!provider || typeof provider.id !== 'string' || !provider.id.trim())
@@ -24,6 +21,9 @@ export function projectModelRoutingMenuOption(provider) {
24
21
  supportsTools: provider.supportsTools !== false && provider.capabilities?.toolUse !== false,
25
22
  supportsStructured: provider.supportsStructured !== false,
26
23
  contextTokens: Number.isFinite(context) && context > 0 ? context : 128_000,
24
+ available: provider.enabled !== false && provider.apiKeyConfigured === true,
25
+ reasoningEffortLevels: modelReasoningLevels(provider),
26
+ defaultReasoningEffort: modelDefaultReasoningEffort(provider),
27
27
  };
28
28
  }
29
29
  const EXPLORER_MIN_CONTEXT = 8_000;
@@ -75,6 +75,8 @@ function inScope(model, policy) {
75
75
  return true;
76
76
  }
77
77
  function missingText(input, reason) {
78
+ if (reason === 'reasoning')
79
+ return '所选模型不支持该推理强度';
78
80
  if (reason === 'auto_pool')
79
81
  return '所选模型不在自动池内';
80
82
  const localOnly = input.projectPolicy?.scope?.localOnly === true;
@@ -226,10 +228,13 @@ export function resolveRoleModel(input) {
226
228
  const chosen = ordered[0];
227
229
  if (!chosen)
228
230
  return fail(input, 'empty');
231
+ const requestedEffort = layer.setting.mode === 'fixed' ? layer.setting.reasoningEffort : undefined;
232
+ if (requestedEffort !== undefined && !chosen.reasoningEffortLevels?.includes(requestedEffort))
233
+ return fail(input, 'reasoning');
229
234
  const source = layer.setting.mode === 'auto' ? 'auto' : layer.source;
230
235
  return {
231
236
  ok: true,
232
- selection: toSelection(chosen),
237
+ selection: { ...toSelection(chosen), ...(requestedEffort !== undefined ? { reasoningEffort: requestedEffort } : {}) },
233
238
  source,
234
239
  ...(input.role === 'verifier'
235
240
  ? { sameFamilyAsWorker: sameFamily(chosen, input.workerModel) }
@@ -0,0 +1,30 @@
1
+ import type { DelegationEvent } from './delegation.ts';
2
+ export type ProjectRecoveryFailureKind = 'response_headers_timeout' | 'network' | 'stream_interrupted' | 'provider_transient' | 'rate_limited' | 'authentication' | 'invalid_request' | 'configuration' | 'permission' | 'budget_exhausted' | 'execution_outcome_unknown' | 'cancelled' | 'fatal';
3
+ /** Produced by the host request boundary; never inferred from assistant prose. */
4
+ export interface ProviderRequestRecovery {
5
+ readonly kind: ProjectRecoveryFailureKind;
6
+ readonly phase?: 'response_headers' | 'stream' | 'request';
7
+ readonly requestId?: string;
8
+ readonly attempts?: number;
9
+ readonly maxAttempts?: number;
10
+ readonly exhausted?: boolean;
11
+ readonly replaySafe?: boolean;
12
+ readonly retryable: boolean;
13
+ }
14
+ /** Legacy diagnostics are admitted only at this seam; structured host failure takes precedence. */
15
+ export declare function classifyProjectAgentFailure(reason: unknown, detail?: unknown): {
16
+ kind: ProjectRecoveryFailureKind;
17
+ retryable: boolean;
18
+ };
19
+ /** Host failure classification, including the persisted diagnostic prefix used by older cards. */
20
+ export declare function projectAgentFailureKind(reason: unknown): 'budget_exhausted' | 'unavailable';
21
+ /** Durable host facts for an explicit retry; never a new user authorization. */
22
+ export interface ProjectAgentTurnRecovery {
23
+ readonly events: readonly DelegationEvent[];
24
+ readonly throughSeq: number;
25
+ }
26
+ /** Factual recovery data returned by post_reply after anchor validation fails. */
27
+ export interface ReplyAnchorCandidate {
28
+ readonly messageId: string;
29
+ readonly text: string;
30
+ }
@@ -0,0 +1,44 @@
1
+ const RECOVERABLE = new Set(['response_headers_timeout', 'network', 'stream_interrupted', 'provider_transient', 'rate_limited']);
2
+ const FAILURE_KINDS = new Set([...RECOVERABLE, 'authentication', 'invalid_request', 'configuration', 'permission', 'budget_exhausted', 'execution_outcome_unknown', 'cancelled', 'fatal']);
3
+ /** Legacy diagnostics are admitted only at this seam; structured host failure takes precedence. */
4
+ export function classifyProjectAgentFailure(reason, detail) {
5
+ if (detail && typeof detail === 'object' && 'kind' in detail && FAILURE_KINDS.has(detail.kind)) {
6
+ const kind = detail.kind;
7
+ return { kind, retryable: RECOVERABLE.has(kind) && !('retryable' in detail && detail.retryable === false) };
8
+ }
9
+ const code = typeof reason === 'string' ? reason.trim().replace(/^代理暂时不可用:\s*/, '') : '';
10
+ let kind = 'fatal';
11
+ if (/^(agent_tool_budget_exhausted|agent_loop_exhausted|work_budget_limited)(?:\s*:|$)/.test(code))
12
+ kind = 'budget_exhausted';
13
+ else if (/^(execution_outcome_unknown|checkpoint_persistence_failed)(?:\s*:|$)/.test(code))
14
+ kind = 'execution_outcome_unknown';
15
+ else if (/^(work_execution_stopped|aborted|AbortError|user_stopped)(?:\s*:|$)/i.test(code))
16
+ kind = 'cancelled';
17
+ else if (/^(permission_denied|permission_revoked|authorization_denied)(?:\s*:|$)/i.test(code))
18
+ kind = 'permission';
19
+ else if (/^(connect timeout after|response_headers_timeout)|ConnectTimeoutError/.test(code))
20
+ kind = 'response_headers_timeout';
21
+ else if (/^(provider_stream_idle_timeout|provider_stream_interrupted)(?:\s*:|$)/.test(code))
22
+ kind = 'stream_interrupted';
23
+ else if (/^(HTTP\s*)?(401|403)(?:\s|:|$)|^(authentication_error|invalid_api_key|credential_unavailable)(?:\s*:|$)/i.test(code))
24
+ kind = 'authentication';
25
+ else if (/^(HTTP\s*)?429(?:\s|:|$)/i.test(code))
26
+ kind = 'rate_limited';
27
+ else if (/^(HTTP\s*)?(500|502|503|504)(?:\s|:|$)|^(server_error|server_is_overloaded)(?:\s*:|$)/i.test(code))
28
+ kind = 'provider_transient';
29
+ else if (/^(HTTP\s*)?(400|404|422)(?:\s|:|$)|^(invalid_request|provider_checkpoint_mismatch)(?:\s*:|$)/i.test(code))
30
+ kind = 'invalid_request';
31
+ else if (/^(CERT_|ERR_CERT_|UNABLE_TO_VERIFY|SELF_SIGNED|DEPTH_ZERO_SELF_SIGNED_CERT|provider_not_configured|work_budget_host_unavailable)/i.test(code))
32
+ kind = 'configuration';
33
+ else if (/^(fetch failed|network|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EAI_AGAIN|UND_ERR_(SOCKET|CONNECT_TIMEOUT)|(?:net::)?ERR_(CONNECTION|NETWORK|TIMED_OUT|NAME_NOT_RESOLVED|PROXY_CONNECTION_FAILED|TUNNEL_CONNECTION_FAILED|SOCKS_CONNECTION_FAILED|INTERNET_DISCONNECTED))/i.test(code))
34
+ kind = 'network';
35
+ return { kind, retryable: RECOVERABLE.has(kind) };
36
+ }
37
+ /** Host failure classification, including the persisted diagnostic prefix used by older cards. */
38
+ export function projectAgentFailureKind(reason) {
39
+ if (typeof reason !== 'string')
40
+ return 'unavailable';
41
+ const code = reason.trim().replace(/^代理暂时不可用:\s*/, '');
42
+ return /^(agent_tool_budget_exhausted|agent_loop_exhausted|work_budget_limited)(?:\s*:|$)/.test(code)
43
+ ? 'budget_exhausted' : 'unavailable';
44
+ }
package/dist/project.d.ts CHANGED
@@ -189,6 +189,59 @@ export interface BotListFilter {
189
189
  readonly query?: string;
190
190
  readonly needsYouOnly?: boolean;
191
191
  }
192
+ /** Bounded, redacted display preview; never an execution or Evidence object. */
193
+ export interface ProjectAgentToolPreview {
194
+ readonly text: string;
195
+ readonly truncated: boolean;
196
+ readonly redacted: boolean;
197
+ }
198
+ export interface ProjectAgentToolActivity {
199
+ readonly kind: 'tool';
200
+ readonly id: string;
201
+ readonly name: string;
202
+ readonly status: 'preparing' | 'running' | 'awaiting_permission' | 'done' | 'error' | 'stopped';
203
+ readonly startedAt?: string;
204
+ readonly finishedAt?: string;
205
+ readonly summary?: string;
206
+ readonly input?: ProjectAgentToolPreview;
207
+ readonly result?: ProjectAgentToolPreview;
208
+ readonly receivedChars?: number;
209
+ readonly permissionDeadlineAt?: string;
210
+ }
211
+ /** Public conversation update, never hidden reasoning, Tool Result or Evidence.
212
+ * User agent_turn records may persist these as publicUpdates (100 / 32000 chars).
213
+ * Legacy rounds[].text is not a public-update source.
214
+ */
215
+ export interface ProjectAgentPublicUpdate {
216
+ readonly id: string;
217
+ readonly text: string;
218
+ }
219
+ /** Ephemeral interactive-turn presentation, including explicit wake retries. No hidden reasoning or Evidence. */
220
+ export interface ProjectAgentActivity {
221
+ readonly workspaceId: string;
222
+ readonly conversationId: string;
223
+ readonly turnId: string;
224
+ readonly revision: number;
225
+ readonly startedAt: string;
226
+ readonly finishedAt?: string;
227
+ readonly modelSelection?: Pick<import('./model-routing.ts').RuntimeModelSelection, 'modelProviderId' | 'reasoningEffort'>;
228
+ readonly replyTo: readonly string[];
229
+ readonly phase: 'waiting' | 'thinking' | 'responding' | 'tool' | 'awaiting_permission' | 'settling' | 'done' | 'error' | 'stopped' | 'disposed';
230
+ readonly replyText: string;
231
+ readonly segments: readonly (({
232
+ readonly kind: 'text';
233
+ } & ProjectAgentPublicUpdate) | ProjectAgentToolActivity)[];
234
+ }
235
+ export interface ProjectAgentStopResponseRequest {
236
+ readonly workspaceId: string;
237
+ readonly turnId: string;
238
+ }
239
+ export type ProjectAgentStopResponseResult = {
240
+ readonly ok: true;
241
+ } | {
242
+ readonly ok: false;
243
+ readonly code: 'PROJECT_AGENT_DISABLED' | 'NOT_FOUND' | 'HOST_OFFLINE' | 'STALE_TURN' | 'INVALID_INPUT';
244
+ };
192
245
  export interface BotListSession {
193
246
  readonly status: WorkSessionStatus;
194
247
  readonly updatedAt?: string;
@@ -0,0 +1,19 @@
1
+ import type { WorkSessionStatus } from './delegation.ts';
2
+ export interface SessionFactSnapshot {
3
+ readonly status: WorkSessionStatus;
4
+ readonly verificationActive: boolean;
5
+ readonly needsUser: boolean;
6
+ readonly blockedReason?: string;
7
+ }
8
+ export declare function deriveSessionFacts(input: {
9
+ status?: string;
10
+ phase?: string;
11
+ runnerStatus?: string;
12
+ accepted?: boolean;
13
+ superseded?: boolean;
14
+ needsUser?: boolean;
15
+ blockedReason?: string;
16
+ verificationActive?: boolean;
17
+ cancellationPhase?: string;
18
+ takeoverPhase?: string;
19
+ }): SessionFactSnapshot;
@@ -0,0 +1,41 @@
1
+ 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 } : {}) };
41
+ }
@@ -240,12 +240,16 @@ export interface ConversationProjectionSnapshot {
240
240
  readonly providerLabel?: string;
241
241
  }
242
242
  export interface GoalPlanProjectionSnapshot {
243
+ readonly needsUser?: boolean;
244
+ readonly blockedReason?: string;
243
245
  readonly planId: string;
244
246
  readonly status: GoalPlanStatus;
245
247
  /** Runner 实时态;Plan 未进入自驱时为 undefined。 */
246
248
  readonly runnerStatus?: GoalRunnerStatus;
247
249
  /** Runner 阻塞是否由系统基础设施持有,而不是用户行动权。 */
248
250
  readonly systemBlocked?: boolean;
251
+ /** A delegated worker is coordinating with its parent, not asking the human. */
252
+ readonly agentWaiting?: boolean;
249
253
  /**
250
254
  * 同一会话此刻是否有前台活流(正在输出 / 调工具 / compact)。
251
255
  * 由聚合层从 listActiveStreams 写入;协议层只认这个布尔事实。
@@ -271,6 +271,9 @@ function decideGoalPlan(snapshot) {
271
271
  }
272
272
  const planStillActive = status === 'executing' || status === 'accepted' || status === 'approved';
273
273
  const conversationLive = snapshot.conversationLive === true;
274
+ if (snapshot.agentWaiting && runnerStatus !== 'waiting_user' && ['executing', 'completed'].includes(status)) {
275
+ return { actionRight: 'peer_advancing', nextAction: 'none', statusLabel: '等待主 Bot 答复', actionLabel: '' };
276
+ }
274
277
  const recoverableSystemBlocked = runnerStatus === 'blocked'
275
278
  && snapshot.systemBlocked === true;
276
279
  // System infrastructure failures are not user decisions. A foreground turn may
@@ -0,0 +1,4 @@
1
+ import type { ProjectAgentToolPreview } from './project.ts';
2
+ /** One bounded display seam for tool parameters/results in live and historical presentation. It never executes a tool. */
3
+ export declare function toolActivityPreview(value: unknown, limit: number): ProjectAgentToolPreview;
4
+ export declare function toolActivitySummary(input: Readonly<Record<string, unknown>> | null | undefined): string;
@@ -0,0 +1,72 @@
1
+ const PRIVATE_FIELD = /(?:api.?key|token|secret|password|credential|authorization|cookie|private.?key|reasoning|thinking)/i;
2
+ /** One bounded display seam for tool parameters/results in live and historical presentation. It never executes a tool. */
3
+ export function toolActivityPreview(value, limit) {
4
+ // A missing result is not the JSON literal null. Stringifying it prints the word "null".
5
+ if (value == null)
6
+ return { text: '', truncated: false, redacted: false };
7
+ if (typeof value === 'string' && value.length > 64_000)
8
+ return { text: '', truncated: true, redacted: true };
9
+ let redacted = false, truncated = false, nodes = 0;
10
+ const cleanText = (text) => {
11
+ const bounded = text.slice(0, 6000);
12
+ if (bounded.length < text.length)
13
+ truncated = true;
14
+ const clean = bounded
15
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, '[redacted]')
16
+ .replace(/AKIA[0-9A-Z]{16}/g, '[redacted]')
17
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, 'Bearer [redacted]')
18
+ .replace(/((?:api[_-]?key|token|secret|password|authorization|cookie)\s*["']?\s*[:=]\s*["']?)[^\s,"';}]+/gi, '$1[redacted]')
19
+ .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*/g, '[redacted]');
20
+ if (clean !== bounded)
21
+ redacted = true;
22
+ return clean;
23
+ };
24
+ const visit = (item, depth = 0) => {
25
+ if (++nodes > 160 || depth > 6) {
26
+ truncated = true;
27
+ return '[truncated]';
28
+ }
29
+ if (typeof item === 'string')
30
+ return cleanText(item);
31
+ if (item == null || typeof item === 'boolean' || typeof item === 'number')
32
+ return item;
33
+ if (Array.isArray(item)) {
34
+ if (item.length > 40)
35
+ truncated = true;
36
+ return item.slice(0, 40).map(child => visit(child, depth + 1));
37
+ }
38
+ if (typeof item === 'object') {
39
+ const fields = [];
40
+ for (const key in item) {
41
+ if (!Object.hasOwn(item, key))
42
+ continue;
43
+ if (fields.length >= 40) {
44
+ truncated = true;
45
+ break;
46
+ }
47
+ if (PRIVATE_FIELD.test(key)) {
48
+ redacted = true;
49
+ fields.push([key, '[redacted]']);
50
+ }
51
+ else
52
+ fields.push([cleanText(key), visit(item[key], depth + 1)]);
53
+ }
54
+ return Object.fromEntries(fields);
55
+ }
56
+ return String(item);
57
+ };
58
+ let parsed = value;
59
+ if (typeof value === 'string') {
60
+ try {
61
+ parsed = JSON.parse(value);
62
+ }
63
+ catch { /* Plain terminal/file output. */ }
64
+ }
65
+ const clean = visit(parsed);
66
+ const text = typeof clean === 'string' ? clean : JSON.stringify(clean ?? null, null, 2);
67
+ return { text: text.slice(0, limit), truncated: truncated || text.length > limit, redacted };
68
+ }
69
+ export function toolActivitySummary(input) {
70
+ const value = input?.path ?? input?.command ?? input?.cmd ?? input?.query ?? input?.title;
71
+ return typeof value === 'string' ? toolActivityPreview(value.replace(/\s+/g, ' ').trim(), 160).text : '';
72
+ }
@@ -0,0 +1,136 @@
1
+ import type { ProjectRecoveryFailureKind } from './project-agent-failure.ts';
2
+ export interface ProjectWorkBudgetLimits {
3
+ readonly schemaVersion?: 2;
4
+ readonly source: string;
5
+ readonly maxModelRequests?: number;
6
+ readonly maxToolCalls?: number;
7
+ readonly maxTokens?: number;
8
+ readonly maxCostUsd?: number;
9
+ }
10
+ export interface ProjectWorkBudgetBoundary {
11
+ readonly metric: 'modelRequests' | 'toolCalls' | 'tokens' | 'costUsd';
12
+ readonly used: number | null;
13
+ readonly limit: number;
14
+ readonly source: string;
15
+ readonly reason: 'limit_reached' | 'usage_unknown' | 'reservation_pending';
16
+ }
17
+ /** Current host admission; a card action never grants execution authority. */
18
+ export interface ProjectReplyRecoveryAction {
19
+ readonly canContinue: boolean;
20
+ readonly blockedReason?: string;
21
+ readonly budget?: ProjectWorkBudgetBoundary;
22
+ }
23
+ /** A reply attempt and delegated execution have independent outcomes. Host facts only. */
24
+ export interface ProjectReplyFailureStatus {
25
+ readonly phase: 'current' | 'retrying' | 'superseded' | 'recovered' | 'cancelled' | 'paused';
26
+ readonly turnKind: 'user' | 'wake';
27
+ readonly workId?: string;
28
+ readonly activeSessionIds: readonly string[];
29
+ readonly recoveredByReplyId?: string;
30
+ }
31
+ /** Persisted on agent_turn.meta and the protected outcome; not a delivered reply. */
32
+ export interface ProjectAgentSilentWait {
33
+ readonly source: 'host' | 'tool';
34
+ readonly sessionIds: readonly string[];
35
+ }
36
+ /** Local host reservation; neither model text nor a UI timer owns recovery. */
37
+ export interface ProjectWorkRecovery {
38
+ readonly failureKind: ProjectRecoveryFailureKind;
39
+ readonly retryable: boolean;
40
+ readonly autoAttempts: number;
41
+ readonly failedTurnId: string;
42
+ readonly retryAt?: string;
43
+ readonly reservationId?: string;
44
+ readonly deadlineAt?: string;
45
+ readonly dispatchesReconciled?: boolean;
46
+ readonly blockedCode?: 'RECOVERY_CHECKPOINT_UNAVAILABLE';
47
+ }
48
+ export type ProjectWorkState = 'runnable' | 'waiting_children' | 'waiting_user' | 'retry_wait' | 'paused' | 'budget_limited' | 'blocked_system' | 'delivered' | 'cancelled' | 'coalesced';
49
+ export type ProjectTurnEnd = 'reply_committed' | 'awaiting_children' | 'yielded' | 'awaiting_user' | 'budget_limited' | 'provider_retryable' | 'no_progress' | 'user_stopped' | 'fatal' | 'coalesced';
50
+ /** Host reconciliation closes an interrupted review, never supplies its verdict. */
51
+ export interface VerificationDispatchReconciliation {
52
+ readonly attemptId: string;
53
+ readonly toolCallId: string;
54
+ readonly capabilityId: 'verify_session' | 'local.delegation.verify_session';
55
+ readonly sessionId: string;
56
+ readonly planId: string;
57
+ readonly sourceRevision: string;
58
+ readonly outcome: 'verification_interrupted';
59
+ readonly at: string;
60
+ }
61
+ export interface ProjectWorkReceipt {
62
+ readonly schemaVersion: 1;
63
+ readonly workId: string;
64
+ readonly workspaceId: string;
65
+ readonly parentConversationId: string;
66
+ readonly anchorInputIds: readonly string[];
67
+ readonly sessionIds: readonly string[];
68
+ /** Current owned technical blockers; a public progress update does not discharge them. */
69
+ readonly repairSessionIds?: readonly string[];
70
+ readonly progressFacts?: readonly string[];
71
+ readonly state: ProjectWorkState;
72
+ readonly revision: number;
73
+ readonly checkpointRef?: string;
74
+ readonly nativeCheckpointRef?: string;
75
+ /** Only duplicate background observations transfer custody; all history remains. */
76
+ readonly continuationOwnerWorkId?: string;
77
+ readonly reportedWait?: {
78
+ readonly replyIds: readonly string[];
79
+ readonly waitingUser: boolean;
80
+ readonly sessionStates: readonly {
81
+ readonly sessionId: string;
82
+ readonly status: string;
83
+ readonly sourceRevision: string;
84
+ readonly observationRevision?: string;
85
+ }[];
86
+ };
87
+ readonly recovery?: ProjectWorkRecovery;
88
+ readonly end?: ProjectTurnEnd;
89
+ readonly attemptId?: string;
90
+ readonly pendingEventIds?: readonly string[];
91
+ readonly waitFor: readonly {
92
+ readonly kind: 'session' | 'approval' | 'question' | 'retry_timer';
93
+ readonly id: string;
94
+ }[];
95
+ readonly consumedEventIds: readonly string[];
96
+ readonly pendingResultRefs: readonly string[];
97
+ readonly lastDeliveredFactKey?: string;
98
+ readonly budgetRef?: string;
99
+ readonly budget?: {
100
+ readonly modelRequests: number;
101
+ readonly toolCalls: number;
102
+ readonly tokens: number;
103
+ readonly costUsd: number;
104
+ readonly unknownUsage: boolean;
105
+ readonly unknownCost: boolean;
106
+ readonly limits: ProjectWorkBudgetLimits;
107
+ readonly policyMigration?: {
108
+ readonly version: 2;
109
+ readonly reason: 'legacy_system_default_removed';
110
+ readonly previousLimits: ProjectWorkBudgetLimits;
111
+ readonly at: string;
112
+ };
113
+ readonly lastBoundary?: ProjectWorkBudgetBoundary;
114
+ readonly attempts: Readonly<Record<string, {
115
+ readonly role: string;
116
+ readonly requests?: number;
117
+ readonly modelProviderId?: string;
118
+ readonly checkpointRef?: string;
119
+ readonly pendingTools?: readonly {
120
+ readonly toolCallId: string | null;
121
+ readonly capabilityId: string | null;
122
+ readonly verificationSessionId?: string;
123
+ }[];
124
+ }>>;
125
+ readonly reconciledDispatches?: readonly VerificationDispatchReconciliation[];
126
+ readonly uncertainDispatches?: readonly {
127
+ readonly attemptId: string;
128
+ readonly role: string;
129
+ readonly toolCallId: string | null;
130
+ readonly capabilityId: string | null;
131
+ readonly verificationSessionId?: string;
132
+ }[];
133
+ };
134
+ readonly stopScope: 'reply' | 'work';
135
+ readonly updatedAt: string;
136
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/protocol",
3
- "version": "0.1.0-rc.2",
3
+ "version": "0.1.0-rc.21",
4
4
  "description": "Shared host-neutral protocol contracts for Peer Agent runtimes and clients.",
5
5
  "type": "module",
6
6
  "license": "MIT",