@peer-agent/protocol 0.0.17 → 0.1.0-beta.1

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,253 @@
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
+ */
5
+ import type { ModelSelectionSnapshot } from './model-routing.ts';
6
+ import { type GoalPlanProjectionSnapshot, type TaskOverviewItem } from './task-overview.ts';
7
+ export type WorkSessionStatus = 'queued' | 'starting' | 'running' | 'waiting_user' | 'verifying' | 'result_ready' | 'accepted' | 'failed' | 'cancelled' | 'superseded';
8
+ export type InputSurface = 'desktop' | 'quick_chat' | 'tui' | 'remote';
9
+ export interface DelegationOrigin {
10
+ readonly anchorMessageId: string;
11
+ readonly inputId: string;
12
+ readonly surface: InputSurface;
13
+ readonly memorySnapshotId: string;
14
+ readonly objectiveId?: string;
15
+ readonly modelSelection: ModelSelectionSnapshot;
16
+ readonly parentSessionId?: string;
17
+ readonly depth: number;
18
+ }
19
+ export interface WorkSessionConversationMeta {
20
+ readonly sessionId?: string;
21
+ readonly workspaceId: string;
22
+ readonly spawnedAt?: string;
23
+ readonly origin: DelegationOrigin;
24
+ readonly supersededBy?: string;
25
+ readonly acceptance?: 'auto' | 'confirm';
26
+ readonly accepted?: boolean;
27
+ readonly verifying?: boolean;
28
+ readonly phase?: 'starting' | 'verifying';
29
+ }
30
+ export interface WorkSession {
31
+ readonly sessionId: string;
32
+ readonly workspaceId: string;
33
+ readonly title: string;
34
+ readonly planId: string | null;
35
+ readonly status: WorkSessionStatus;
36
+ readonly actionRight: TaskOverviewItem['actionRight'];
37
+ readonly nextAction: TaskOverviewItem['nextAction'];
38
+ readonly statusLabel: string;
39
+ readonly needsYouReason?: TaskOverviewItem['needsYouReason'];
40
+ readonly spawnedAt: string;
41
+ readonly origin: DelegationOrigin;
42
+ readonly supersededBy?: string;
43
+ }
44
+ export interface SessionReport {
45
+ readonly sessionId: string;
46
+ readonly planId: string | null;
47
+ readonly status: WorkSessionStatus;
48
+ readonly summary: string;
49
+ readonly keyFindings: readonly string[];
50
+ readonly changedFiles: readonly {
51
+ readonly path: string;
52
+ readonly summary: string;
53
+ }[];
54
+ readonly evidenceRefs: readonly string[];
55
+ }
56
+ export type DelegationEventKind = 'session_spawned' | 'session_progress' | 'session_needs_user' | 'session_verified' | 'session_ended' | 'user_intervened' | 'objective_signal' | 'digest_due';
57
+ export type JsonValue = null | string | number | boolean | readonly JsonValue[] | {
58
+ readonly [key: string]: JsonValue;
59
+ };
60
+ export interface DelegationEvent {
61
+ readonly eventId: string;
62
+ readonly kind: DelegationEventKind;
63
+ readonly sessionId: string;
64
+ readonly at: string;
65
+ readonly payload: JsonValue;
66
+ }
67
+ export interface AgentReplyMeta {
68
+ readonly replyTo: readonly string[];
69
+ readonly sources: readonly string[];
70
+ readonly verdictRef?: string;
71
+ readonly memoryUsed: readonly string[];
72
+ readonly memoryLearned: readonly string[];
73
+ readonly surfacing: 'interrupt' | 'message' | 'digest' | 'silent';
74
+ }
75
+ export type MessageDisposition = {
76
+ readonly kind: 'answered';
77
+ readonly messageId: string;
78
+ readonly replyMessageIds: readonly string[];
79
+ } | {
80
+ readonly kind: 'merged';
81
+ readonly messageId: string;
82
+ readonly sessionId: string;
83
+ } | {
84
+ readonly kind: 'stopped';
85
+ readonly messageId: string;
86
+ readonly sessionIds: readonly string[];
87
+ readonly reason: string;
88
+ } | {
89
+ readonly kind: 'superseded';
90
+ readonly messageId: string;
91
+ readonly oldSessionId: string;
92
+ readonly newSessionId: string;
93
+ readonly reason: string;
94
+ } | {
95
+ readonly kind: 'parallel';
96
+ readonly messageId: string;
97
+ readonly sessionIds: readonly string[];
98
+ } | {
99
+ readonly kind: 'queued';
100
+ readonly messageId: string;
101
+ readonly sessionId: string;
102
+ readonly dependsOn: readonly string[];
103
+ } | {
104
+ readonly kind: 'out_of_scope';
105
+ readonly messageId: string;
106
+ readonly sessionId: string;
107
+ };
108
+ export interface DispositionMessage {
109
+ readonly id: string;
110
+ readonly role: 'user' | 'assistant';
111
+ readonly replyTo?: readonly string[];
112
+ readonly quoteSessionIds?: readonly string[];
113
+ }
114
+ export interface DispositionEvent {
115
+ readonly kind: 'spawn' | 'merge' | 'stop' | 'supersede' | 'parallel' | 'queue';
116
+ readonly anchorMessageId: string;
117
+ readonly sessionId?: string;
118
+ readonly sessionIds?: readonly string[];
119
+ readonly dependsOn?: readonly string[];
120
+ readonly reason?: string;
121
+ readonly oldSessionId?: string;
122
+ readonly newSessionId?: string;
123
+ readonly replyMessageId?: string;
124
+ }
125
+ export type VerificationOutcome = 'passed' | 'failed' | 'partial' | 'unverifiable';
126
+ export type IndependentVerifierState = 'passed' | 'failed' | 'not_required' | 'missing';
127
+ export interface VerificationCheck {
128
+ readonly name: string;
129
+ readonly passed: boolean;
130
+ readonly reason?: string;
131
+ }
132
+ export interface VerificationVerdict {
133
+ readonly outcome: VerificationOutcome;
134
+ readonly independentVerifier: IndependentVerifierState;
135
+ readonly verifierModel?: string;
136
+ readonly sameFamilyAsWorker?: boolean;
137
+ readonly checks: readonly VerificationCheck[];
138
+ readonly evidenceRefs: readonly string[];
139
+ }
140
+ export type AcceptancePolicy = 'auto' | 'confirm';
141
+ export type AcceptanceReason = 'verdict_not_passed' | 'manual_criteria_pending' | 'external_side_effects' | 'destructive_operation' | 'out_of_scope_write' | 'project_requires_confirm' | 'user_requested_review' | 'verification_below_floor';
142
+ export interface AcceptanceDecision {
143
+ readonly mode: AcceptancePolicy;
144
+ readonly acceptedBy?: 'policy' | 'user';
145
+ readonly reasons: readonly AcceptanceReason[];
146
+ }
147
+ export interface AcceptanceSessionFacts {
148
+ readonly manualCriteriaPending?: boolean;
149
+ readonly externalSideEffects?: boolean;
150
+ readonly destructiveOperation?: boolean;
151
+ readonly outOfScopeWrite?: boolean;
152
+ readonly userRequestedReview?: boolean;
153
+ readonly verificationBelowFloor?: boolean;
154
+ /** The agent has already posted the reply that explains this result. */
155
+ readonly reported?: boolean;
156
+ /** Acceptance close gate. Policy acceptance does not proceed when this is false. */
157
+ readonly closeGatePassed?: boolean;
158
+ }
159
+ export type Surfacing = 'interrupt' | 'message' | 'digest' | 'silent';
160
+ export interface SurfacingDecision {
161
+ readonly decision: Surfacing;
162
+ readonly reason: string;
163
+ }
164
+ export interface SurfacingEvent {
165
+ readonly origin: 'user_request' | 'objective_signal' | 'agent_idea';
166
+ readonly kind: 'needs_user' | 'confirm' | 'failure_needs_decision' | 'result' | 'observation' | 'idea' | 'objective_risk';
167
+ readonly novelty: boolean;
168
+ readonly severity: 'info' | 'notable' | 'urgent';
169
+ readonly deadlineImminent?: boolean;
170
+ }
171
+ export interface ProjectInput {
172
+ readonly inputId: string;
173
+ readonly workspaceId: string;
174
+ readonly surface: InputSurface;
175
+ readonly text: string;
176
+ readonly anchorRefs: readonly string[];
177
+ readonly quoteRefs: readonly string[];
178
+ readonly attachmentRefs: readonly string[];
179
+ readonly createdAt: string;
180
+ }
181
+ export type PendingApprovalState = 'open' | 'approved' | 'denied' | 'expired' | 'stale';
182
+ export interface PendingApproval {
183
+ readonly approvalId: string;
184
+ readonly workspaceId: string | null;
185
+ readonly sessionId?: string | null;
186
+ readonly conversationId?: string | null;
187
+ readonly planId: string | null;
188
+ readonly toolCallId?: string;
189
+ readonly streamId: string;
190
+ readonly capabilityId: string;
191
+ readonly summary: string;
192
+ readonly riskLevel: string;
193
+ readonly argsDigest: string;
194
+ readonly createdAt: string;
195
+ readonly state: PendingApprovalState;
196
+ readonly decidedAt?: string;
197
+ readonly decidedBy?: 'local_ui' | 'policy';
198
+ }
199
+ export interface HostLease {
200
+ readonly hostId: string;
201
+ readonly surface: 'desktop' | 'tui';
202
+ readonly pid: number;
203
+ readonly appVersion: string;
204
+ readonly acquiredAt: string;
205
+ readonly heartbeatAt: string;
206
+ }
207
+ export declare function delegationEventId(input: {
208
+ readonly kind: DelegationEventKind;
209
+ readonly sessionId: string;
210
+ readonly at: string;
211
+ readonly payload: JsonValue;
212
+ }): string;
213
+ export declare function createDelegationEvent(input: {
214
+ readonly kind: DelegationEventKind;
215
+ readonly sessionId: string;
216
+ readonly at: string;
217
+ readonly payload?: JsonValue;
218
+ }): DelegationEvent;
219
+ /**
220
+ * Project a GoalPlan snapshot into a work session.
221
+ * actionRight / nextAction / statusLabel come from projectGoalPlan, so the two projections cannot disagree.
222
+ * A paused plan has no delegation status of its own; it is queued, and the visible conclusion stays paused.
223
+ */
224
+ export declare function projectWorkSession(plan: GoalPlanProjectionSnapshot, conversationMeta: WorkSessionConversationMeta): WorkSession;
225
+ /**
226
+ * Dispositions are a projection of anchor events plus replies.
227
+ * The assistant text answers the last user message in the turn unless replyTo says otherwise.
228
+ * A quote limits message/cancel/supersede to those sessions; anything else is out_of_scope.
229
+ */
230
+ export declare function projectMessageDispositions(messages: readonly DispositionMessage[], events: readonly DispositionEvent[]): MessageDisposition[];
231
+ /**
232
+ * Surfacing table from the delegation runtime, top to bottom.
233
+ * foreground does not change the row. needsYou uses the same row as needs_user.
234
+ */
235
+ export declare function decideSurfacing(input: {
236
+ readonly event: SurfacingEvent;
237
+ readonly proactivity: 'off' | 'low' | 'normal' | 'high';
238
+ readonly foreground: boolean;
239
+ readonly quietHours: boolean;
240
+ readonly needsYou: boolean;
241
+ }): SurfacingDecision;
242
+ /**
243
+ * Policy acceptance ignores userOverride. It also requires a posted reply and a passed close gate.
244
+ * A user override can record acceptedBy user on a confirm decision; it cannot mint a policy acceptance.
245
+ */
246
+ export declare function decideAcceptance(input: {
247
+ readonly verdict: VerificationVerdict;
248
+ readonly policy: AcceptancePolicy;
249
+ readonly session: AcceptanceSessionFacts;
250
+ readonly userOverride?: {
251
+ readonly accept: boolean;
252
+ } | null;
253
+ }): AcceptanceDecision;
@@ -0,0 +1,268 @@
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
+ */
5
+ import { projectGoalPlan, } from "./task-overview.js";
6
+ function fnv1a(text) {
7
+ let hash = 0x811c9dc5;
8
+ for (let index = 0; index < text.length; index += 1) {
9
+ hash ^= text.charCodeAt(index);
10
+ hash = Math.imul(hash, 0x01000193);
11
+ }
12
+ return hash >>> 0;
13
+ }
14
+ function stableStringify(value) {
15
+ if (value === null || typeof value !== 'object')
16
+ return JSON.stringify(value);
17
+ if (Array.isArray(value))
18
+ return `[${value.map((item) => stableStringify(item)).join(',')}]`;
19
+ const record = value;
20
+ const keys = Object.keys(record).sort();
21
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key] ?? null)}`).join(',')}}`;
22
+ }
23
+ export function delegationEventId(input) {
24
+ const body = stableStringify({
25
+ at: input.at,
26
+ kind: input.kind,
27
+ payload: input.payload,
28
+ sessionId: input.sessionId,
29
+ });
30
+ const high = fnv1a(body).toString(16).padStart(8, '0');
31
+ const low = fnv1a(`#${body}`).toString(16).padStart(8, '0');
32
+ return `${high}${low}`;
33
+ }
34
+ export function createDelegationEvent(input) {
35
+ const payload = input.payload ?? null;
36
+ return {
37
+ eventId: delegationEventId({ ...input, payload }),
38
+ kind: input.kind,
39
+ sessionId: input.sessionId,
40
+ at: input.at,
41
+ payload,
42
+ };
43
+ }
44
+ function delegationStatus(snapshot, meta, projected) {
45
+ if (meta.supersededBy)
46
+ return 'superseded';
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 (projected.actionRight === 'needs_you')
59
+ return 'waiting_user';
60
+ if (snapshot.runnerStatus === 'exploring' || meta.phase === 'verifying')
61
+ return 'verifying';
62
+ if (meta.phase === 'starting')
63
+ return 'starting';
64
+ if (snapshot.status === 'approved'
65
+ || snapshot.status === 'accepted'
66
+ || snapshot.status === 'paused'
67
+ || snapshot.status === 'interrupted'
68
+ || projected.actionRight === 'paused') {
69
+ return 'queued';
70
+ }
71
+ return 'running';
72
+ }
73
+ /**
74
+ * Project a GoalPlan snapshot into a work session.
75
+ * actionRight / nextAction / statusLabel come from projectGoalPlan, so the two projections cannot disagree.
76
+ * A paused plan has no delegation status of its own; it is queued, and the visible conclusion stays paused.
77
+ */
78
+ export function projectWorkSession(plan, conversationMeta) {
79
+ const projected = projectGoalPlan(plan);
80
+ return {
81
+ sessionId: conversationMeta.sessionId ?? plan.conversationId ?? plan.planId,
82
+ workspaceId: conversationMeta.workspaceId,
83
+ title: plan.title,
84
+ planId: plan.planId,
85
+ status: delegationStatus(plan, conversationMeta, projected),
86
+ actionRight: projected.actionRight,
87
+ nextAction: projected.nextAction,
88
+ statusLabel: projected.statusLabel,
89
+ ...(projected.needsYouReason ? { needsYouReason: projected.needsYouReason } : {}),
90
+ spawnedAt: conversationMeta.spawnedAt ?? plan.updatedAt ?? '',
91
+ origin: conversationMeta.origin,
92
+ ...(conversationMeta.supersededBy ? { supersededBy: conversationMeta.supersededBy } : {}),
93
+ };
94
+ }
95
+ function eventOutOfScope(message, sessionId) {
96
+ if (!sessionId)
97
+ return false;
98
+ const quoted = message.quoteSessionIds;
99
+ if (!quoted || quoted.length === 0)
100
+ return false;
101
+ return !quoted.includes(sessionId);
102
+ }
103
+ function dispositionFor(message, event) {
104
+ const sessionId = event.sessionId ?? event.sessionIds?.[0] ?? '';
105
+ if (eventOutOfScope(message, sessionId) || (event.sessionIds ?? []).some((id) => eventOutOfScope(message, id))) {
106
+ return { kind: 'out_of_scope', messageId: message.id, sessionId };
107
+ }
108
+ switch (event.kind) {
109
+ case 'merge':
110
+ return { kind: 'merged', messageId: message.id, sessionId };
111
+ case 'stop':
112
+ return {
113
+ kind: 'stopped',
114
+ messageId: message.id,
115
+ sessionIds: event.sessionIds ?? (sessionId ? [sessionId] : []),
116
+ reason: event.reason ?? '',
117
+ };
118
+ case 'supersede':
119
+ return {
120
+ kind: 'superseded',
121
+ messageId: message.id,
122
+ oldSessionId: event.oldSessionId ?? '',
123
+ newSessionId: event.newSessionId ?? sessionId,
124
+ reason: event.reason ?? '',
125
+ };
126
+ case 'parallel':
127
+ return { kind: 'parallel', messageId: message.id, sessionIds: event.sessionIds ?? (sessionId ? [sessionId] : []) };
128
+ case 'queue':
129
+ return { kind: 'queued', messageId: message.id, sessionId, dependsOn: event.dependsOn ?? [] };
130
+ default:
131
+ return { kind: 'parallel', messageId: message.id, sessionIds: event.sessionIds ?? (sessionId ? [sessionId] : []) };
132
+ }
133
+ }
134
+ /**
135
+ * Dispositions are a projection of anchor events plus replies.
136
+ * The assistant text answers the last user message in the turn unless replyTo says otherwise.
137
+ * A quote limits message/cancel/supersede to those sessions; anything else is out_of_scope.
138
+ */
139
+ export function projectMessageDispositions(messages, events) {
140
+ const byId = new Map(messages.map((message) => [message.id, message]));
141
+ const dispositions = [];
142
+ for (const event of events) {
143
+ const message = byId.get(event.anchorMessageId);
144
+ if (!message || message.role !== 'user')
145
+ continue;
146
+ dispositions.push(dispositionFor(message, event));
147
+ }
148
+ for (let index = 0; index < messages.length; index += 1) {
149
+ const message = messages[index];
150
+ if (!message || message.role !== 'assistant')
151
+ continue;
152
+ const targets = message.replyTo && message.replyTo.length > 0
153
+ ? message.replyTo
154
+ : previousUserId(messages, index);
155
+ for (const messageId of targets) {
156
+ dispositions.push({
157
+ kind: 'answered',
158
+ messageId,
159
+ replyMessageIds: [message.id],
160
+ });
161
+ }
162
+ }
163
+ return dispositions;
164
+ }
165
+ function previousUserId(messages, assistantIndex) {
166
+ for (let index = assistantIndex - 1; index >= 0; index -= 1) {
167
+ const message = messages[index];
168
+ if (message?.role === 'user')
169
+ return [message.id];
170
+ if (message?.role === 'assistant')
171
+ break;
172
+ }
173
+ return [];
174
+ }
175
+ const ATTENTION_KINDS = new Set([
176
+ 'needs_user',
177
+ 'confirm',
178
+ 'failure_needs_decision',
179
+ 'objective_risk',
180
+ ]);
181
+ function agentOrigin(origin) {
182
+ return origin === 'agent_idea' || origin === 'objective_signal';
183
+ }
184
+ /**
185
+ * Surfacing table from the delegation runtime, top to bottom.
186
+ * foreground does not change the row. needsYou uses the same row as needs_user.
187
+ */
188
+ export function decideSurfacing(input) {
189
+ void input.foreground;
190
+ const { event, proactivity, quietHours, needsYou } = input;
191
+ if (needsYou || ATTENTION_KINDS.has(event.kind)) {
192
+ const staysInterrupt = event.kind === 'objective_risk' && event.deadlineImminent === true;
193
+ if (quietHours && !staysInterrupt)
194
+ return { decision: 'message', reason: 'quiet_hours' };
195
+ return { decision: 'interrupt', reason: needsYou && !ATTENTION_KINDS.has(event.kind) ? 'needs_you' : 'attention' };
196
+ }
197
+ if (event.origin === 'user_request' && event.kind === 'result') {
198
+ if (proactivity === 'normal' || proactivity === 'high') {
199
+ return { decision: 'interrupt', reason: 'user_result' };
200
+ }
201
+ return { decision: 'message', reason: 'user_result' };
202
+ }
203
+ if (agentOrigin(event.origin) && event.novelty === false) {
204
+ return { decision: 'silent', reason: 'not_novel' };
205
+ }
206
+ if (agentOrigin(event.origin) && event.severity === 'urgent') {
207
+ return { decision: 'interrupt', reason: 'agent_urgent' };
208
+ }
209
+ if (agentOrigin(event.origin) && event.severity === 'notable') {
210
+ const decision = proactivity === 'high'
211
+ ? 'interrupt'
212
+ : proactivity === 'normal'
213
+ ? 'message'
214
+ : 'digest';
215
+ return { decision, reason: 'agent_notable' };
216
+ }
217
+ if (agentOrigin(event.origin) && (event.severity === 'info' || event.kind === 'idea')) {
218
+ const decision = proactivity === 'high'
219
+ ? 'message'
220
+ : proactivity === 'off'
221
+ ? 'silent'
222
+ : 'digest';
223
+ return { decision, reason: 'agent_info' };
224
+ }
225
+ return { decision: 'message', reason: 'default' };
226
+ }
227
+ const CONFIRM_REASON_ORDER = [
228
+ 'verdict_not_passed',
229
+ 'manual_criteria_pending',
230
+ 'external_side_effects',
231
+ 'destructive_operation',
232
+ 'out_of_scope_write',
233
+ 'project_requires_confirm',
234
+ 'user_requested_review',
235
+ 'verification_below_floor',
236
+ ];
237
+ /**
238
+ * Policy acceptance ignores userOverride. It also requires a posted reply and a passed close gate.
239
+ * A user override can record acceptedBy user on a confirm decision; it cannot mint a policy acceptance.
240
+ */
241
+ export function decideAcceptance(input) {
242
+ const reasons = [];
243
+ if (input.verdict.outcome !== 'passed')
244
+ reasons.push('verdict_not_passed');
245
+ if (input.session.manualCriteriaPending === true)
246
+ reasons.push('manual_criteria_pending');
247
+ if (input.session.externalSideEffects === true)
248
+ reasons.push('external_side_effects');
249
+ if (input.session.destructiveOperation === true)
250
+ reasons.push('destructive_operation');
251
+ if (input.session.outOfScopeWrite === true)
252
+ reasons.push('out_of_scope_write');
253
+ if (input.policy === 'confirm')
254
+ reasons.push('project_requires_confirm');
255
+ if (input.session.userRequestedReview === true)
256
+ reasons.push('user_requested_review');
257
+ if (input.session.verificationBelowFloor === true)
258
+ reasons.push('verification_below_floor');
259
+ const ordered = CONFIRM_REASON_ORDER.filter((reason) => reasons.includes(reason));
260
+ const closeGatePassed = input.session.closeGatePassed === true;
261
+ if (ordered.length === 0 && input.policy === 'auto' && input.session.reported === true && closeGatePassed) {
262
+ return { mode: 'auto', acceptedBy: 'policy', reasons: [] };
263
+ }
264
+ if (ordered.length > 0 && input.userOverride?.accept === true && closeGatePassed) {
265
+ return { mode: 'confirm', acceptedBy: 'user', reasons: ordered };
266
+ }
267
+ return { mode: ordered.length > 0 ? 'confirm' : 'auto', reasons: ordered };
268
+ }
package/dist/index.d.ts CHANGED
@@ -619,6 +619,7 @@ export interface LlmModelInfo {
619
619
  readonly modelOptionValues?: LlmModelOptionValues;
620
620
  readonly supportsVision?: boolean;
621
621
  readonly supportsReasoning?: boolean;
622
+ readonly reasoningEffortValues?: readonly string[];
622
623
  readonly metadataSource?: 'provider' | 'models.dev';
623
624
  readonly pricingSource?: 'provider' | 'models.dev-reference';
624
625
  readonly inputPrice?: number;
@@ -862,3 +863,7 @@ export * from './appshot.ts';
862
863
  export * from './automation.ts';
863
864
  export * from './task-overview.ts';
864
865
  export * from './skill-marketplace.ts';
866
+ export * from './delegation.ts';
867
+ export * from './model-routing.ts';
868
+ export * from './project.ts';
869
+ export * from './objectives.ts';
package/dist/index.js CHANGED
@@ -31,3 +31,7 @@ export * from "./appshot.js";
31
31
  export * from "./automation.js";
32
32
  export * from "./task-overview.js";
33
33
  export * from "./skill-marketplace.js";
34
+ export * from "./delegation.js";
35
+ export * from "./model-routing.js";
36
+ export * from "./project.js";
37
+ export * from "./objectives.js";
package/dist/memory.d.ts CHANGED
@@ -1,104 +1,52 @@
1
- export interface WorkingMemorySection {
2
- readonly key: string;
3
- readonly title: string;
4
- readonly content: string;
5
- readonly priority?: number;
6
- readonly source?: 'conversation' | 'agent' | 'local_preview';
7
- }
8
- export interface WorkingMemorySnapshotEntry {
9
- readonly id?: number;
10
- readonly itemType?: string;
11
- readonly title?: string | null;
12
- readonly content: string;
13
- readonly sourceMessageId?: number | null;
14
- readonly sourceRefId?: string | null;
15
- readonly gmtModified?: string | null;
16
- }
17
- export interface WorkingMemorySnapshotJson {
18
- readonly currentGoal?: WorkingMemorySnapshotEntry | null;
19
- readonly constraints?: readonly WorkingMemorySnapshotEntry[];
20
- readonly decisions?: readonly WorkingMemorySnapshotEntry[];
21
- readonly facts?: readonly WorkingMemorySnapshotEntry[];
22
- readonly currentState?: WorkingMemorySnapshotEntry | null;
23
- readonly nextStep?: WorkingMemorySnapshotEntry | null;
24
- readonly abandonedPaths?: readonly WorkingMemorySnapshotEntry[];
25
- readonly keyObjects?: readonly WorkingMemorySnapshotEntry[];
26
- }
27
- export interface WorkingMemoryPromptSection {
28
- readonly scope: 'conversation' | 'agent';
29
- readonly agentId: number;
30
- readonly version: number;
31
- readonly snapshotUuid: string;
32
- readonly renderText: string;
33
- readonly tokenEstimate: number;
34
- readonly snapshotJson?: WorkingMemorySnapshotJson | null;
35
- readonly gmtCreate?: string;
36
- }
37
- export type WorkingMemoryData = readonly WorkingMemoryPromptSection[] | readonly WorkingMemorySection[] | {
38
- readonly conversationId: number;
39
- readonly agentId?: number;
40
- readonly sections: readonly WorkingMemorySection[];
41
- readonly updatedAt?: string;
1
+ /**
2
+ * Project memory contracts. Entries are facts for continuity, not instructions.
3
+ */
4
+ import type { MessageDisposition } from './delegation.ts';
5
+ export type MemoryKind = 'fact' | 'preference' | 'decision' | 'procedure' | 'responsibility';
6
+ export type MemoryTrust = 'verified' | 'stated' | 'inferred';
7
+ export type MemoryStatus = 'active' | 'forgotten' | 'expired' | 'conflicted';
8
+ export interface MemoryItem {
9
+ readonly id: string;
10
+ readonly scope: 'project' | 'user';
11
+ readonly workspaceId?: string;
12
+ readonly kind: MemoryKind;
13
+ readonly text: string;
14
+ readonly trust: MemoryTrust;
15
+ readonly sourceRefs: readonly string[];
16
+ readonly pinned: boolean;
17
+ readonly status: MemoryStatus;
18
+ readonly confirmedCount: number;
19
+ readonly createdAt: string;
20
+ readonly lastUsedAt?: string;
21
+ readonly expiresAt?: string;
22
+ /** The statement was taken from page, file, or tool content rather than the user. */
23
+ readonly untrusted?: boolean;
24
+ }
25
+ export interface MemoryEpisode {
26
+ readonly id: string;
27
+ readonly workspaceId: string;
28
+ readonly anchorMessageId: string;
29
+ readonly dispositions: readonly MessageDisposition[];
30
+ readonly summary: string;
31
+ readonly openedAt: string;
32
+ readonly closedAt: string;
33
+ }
34
+ export interface MemorySnapshot {
35
+ readonly snapshotId: string;
36
+ readonly itemIds: readonly string[];
37
+ readonly createdAt: string;
38
+ }
39
+ export type MemoryAdmission = {
40
+ readonly ok: true;
41
+ } | {
42
+ readonly ok: false;
43
+ readonly reason: string;
42
44
  };
43
- export type MemoryWikiCompileStatus = 'empty' | 'running' | 'completed' | 'failed';
44
- export type MemoryWikiCompileMode = 'full' | 'delta';
45
- export interface InitializeConversationMemoryWikiResult {
46
- readonly conversationId: number;
47
- readonly agentId?: number;
48
- readonly status: MemoryWikiCompileStatus;
49
- readonly mode?: MemoryWikiCompileMode | null;
50
- readonly initialized?: boolean;
51
- readonly enqueuedJobs?: number;
52
- readonly consumedMessageCount?: number;
53
- readonly pageCount?: number;
54
- readonly error?: string;
55
- }
56
- export interface ConversationMemoryWikiStatus {
57
- readonly conversationId?: number;
58
- readonly agentId?: number;
59
- readonly status: 'not_initialized' | 'initializing' | 'ready' | 'failed' | MemoryWikiCompileStatus;
60
- readonly mode?: MemoryWikiCompileMode | null;
61
- readonly pageCount?: number;
62
- readonly totalJobs?: number;
63
- readonly pendingJobs?: number;
64
- readonly runningJobs?: number;
65
- readonly completedJobs?: number;
66
- readonly failedJobs?: number;
67
- readonly skippedJobs?: number;
68
- readonly progressPercent?: number;
69
- readonly canInitialize?: boolean;
70
- readonly updatedAt?: string;
71
- }
72
- export interface ConversationMemoryWikiPage {
73
- readonly pageUuid: string;
74
- readonly pageKey: string;
75
- readonly title: string;
76
- readonly pageType?: string;
77
- readonly scopeType?: string;
78
- readonly summary?: string;
79
- readonly tags?: readonly string[];
80
- readonly importance?: number;
81
- readonly confidence?: number;
82
- readonly version?: number;
83
- readonly markdown?: string;
84
- readonly bodyMd?: string;
85
- readonly structuredJson?: Record<string, unknown> | null;
86
- readonly entities?: readonly unknown[];
87
- readonly evidenceRefs?: readonly unknown[];
88
- readonly updatedAt?: string;
89
- readonly gmtModified?: string | null;
90
- }
91
- export interface ConversationMemoryWikiPageListData {
92
- readonly list?: readonly ConversationMemoryWikiPage[];
93
- readonly pages?: readonly ConversationMemoryWikiPage[];
94
- readonly total?: number;
95
- readonly limit?: number;
96
- readonly offset?: number;
97
- }
98
- export interface ConversationMemoryCompileStatus {
99
- readonly conversationId: number;
100
- readonly agentId?: number;
101
- readonly status: 'idle' | 'running' | 'completed' | 'failed';
102
- readonly consumedMessageCount?: number;
103
- readonly error?: string;
104
- }
45
+ /**
46
+ * Whether a candidate may take effect. Verified items need a resolvable source.
47
+ * Inferred preferences stay inactive until they have been confirmed three times.
48
+ * Secrets, permission loosening, and untrusted standing orders are refused.
49
+ */
50
+ export declare function assessMemoryCandidate(item: MemoryItem, options?: {
51
+ readonly resolvableRefs?: readonly string[];
52
+ }): MemoryAdmission;
package/dist/memory.js CHANGED
@@ -1 +1,38 @@
1
- export {};
1
+ /**
2
+ * Project memory contracts. Entries are facts for continuity, not instructions.
3
+ */
4
+ const SECRET = /sk-[A-Za-z0-9]{8,}|api[_-]?key\s*[:=]|bearer\s+[A-Za-z0-9._\-]{8,}/i;
5
+ const LOOSENING = /不用确认|跳过批准|跳过审批|always allow|skip approval|full_local|不用我批/i;
6
+ const STANDING_ORDER = /以后都|下次都|always do this/i;
7
+ /**
8
+ * Whether a candidate may take effect. Verified items need a resolvable source.
9
+ * Inferred preferences stay inactive until they have been confirmed three times.
10
+ * Secrets, permission loosening, and untrusted standing orders are refused.
11
+ */
12
+ export function assessMemoryCandidate(item, options = {}) {
13
+ if (item.status === 'forgotten' || item.status === 'expired') {
14
+ return { ok: false, reason: 'inactive' };
15
+ }
16
+ if (item.status === 'conflicted')
17
+ return { ok: false, reason: 'conflicted' };
18
+ if (SECRET.test(item.text))
19
+ return { ok: false, reason: 'sensitive' };
20
+ if (LOOSENING.test(item.text))
21
+ return { ok: false, reason: 'loosens_policy' };
22
+ if (item.untrusted === true && (item.kind === 'preference' || STANDING_ORDER.test(item.text))) {
23
+ return { ok: false, reason: 'untrusted_standing_order' };
24
+ }
25
+ if (item.trust === 'verified') {
26
+ const resolvable = options.resolvableRefs;
27
+ if (!resolvable || !item.sourceRefs.some((ref) => resolvable.includes(ref))) {
28
+ return { ok: false, reason: 'evidence_unresolved' };
29
+ }
30
+ }
31
+ if (item.kind === 'preference' && item.trust === 'inferred' && item.confirmedCount < 3) {
32
+ return { ok: false, reason: 'preference_unconfirmed' };
33
+ }
34
+ if (item.trust === 'stated' || item.trust === 'verified' || item.trust === 'inferred') {
35
+ return { ok: true };
36
+ }
37
+ return { ok: false, reason: 'inactive' };
38
+ }
@@ -0,0 +1,100 @@
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
+ */
5
+ export type ModelTier = 'strong' | 'fast' | 'economy' | 'vision';
6
+ export type ModelRole = 'project_agent' | 'session_worker' | 'explorer' | 'verifier' | 'visual_verifier' | 'memory_curator' | 'objective_probe' | 'compactor';
7
+ export type RoleSetting = {
8
+ readonly mode: 'tier';
9
+ readonly tier: ModelTier;
10
+ } | {
11
+ readonly mode: 'fixed';
12
+ readonly modelProviderId: string;
13
+ } | {
14
+ readonly mode: 'auto';
15
+ readonly pool: readonly string[];
16
+ };
17
+ export interface ModelTierBinding {
18
+ readonly primary: string;
19
+ readonly fallbacks?: readonly string[];
20
+ }
21
+ export interface ModelRoutingSettings {
22
+ readonly tiers: Partial<Record<ModelTier, ModelTierBinding>>;
23
+ readonly roles: Partial<Record<ModelRole, RoleSetting>>;
24
+ readonly verifierPreferDifferentFamily: boolean;
25
+ readonly dailySpendCapUsd?: number;
26
+ }
27
+ export interface ProjectModelScope {
28
+ /** Allow-list. A project may only tighten the global set. */
29
+ readonly modelProviderIds?: readonly string[];
30
+ readonly families?: readonly string[];
31
+ readonly localOnly?: boolean;
32
+ }
33
+ export interface ProjectModelPolicy {
34
+ readonly scope?: ProjectModelScope;
35
+ readonly overrides?: Partial<Record<ModelRole, RoleSetting>>;
36
+ }
37
+ export type ModelSelectionSource = 'this_request' | 'task' | 'objective' | 'project' | 'global' | 'auto';
38
+ export interface RuntimeModelSelection {
39
+ readonly providerId: string;
40
+ readonly modelId: string;
41
+ readonly modelProviderId: string;
42
+ readonly reasoningEffort?: string;
43
+ readonly family: string;
44
+ }
45
+ export interface ModelSelectionSnapshot {
46
+ readonly worker: RuntimeModelSelection;
47
+ readonly explorer: RuntimeModelSelection;
48
+ readonly verifier: RuntimeModelSelection & {
49
+ readonly sameFamilyAsWorker: boolean;
50
+ };
51
+ readonly visualVerifier?: RuntimeModelSelection;
52
+ readonly source: Readonly<Record<string, ModelSelectionSource>>;
53
+ readonly autoReason?: string;
54
+ readonly resolvedAt: string;
55
+ }
56
+ export interface CatalogModel {
57
+ readonly modelProviderId: string;
58
+ readonly providerId: string;
59
+ readonly modelId: string;
60
+ readonly family: string;
61
+ readonly tools?: boolean;
62
+ readonly vision?: boolean;
63
+ readonly structured?: boolean;
64
+ readonly contextTokens?: number;
65
+ readonly local?: boolean;
66
+ readonly reasoningEffort?: string;
67
+ }
68
+ export type ModelResolution = {
69
+ readonly ok: true;
70
+ readonly selection: RuntimeModelSelection;
71
+ readonly source: ModelSelectionSource;
72
+ readonly sameFamilyAsWorker?: boolean;
73
+ } | {
74
+ readonly ok: false;
75
+ readonly reason: 'capability' | 'scope' | 'auto_pool' | 'empty';
76
+ readonly missing: string;
77
+ };
78
+ export interface RoleModelRequest {
79
+ readonly role: ModelRole;
80
+ readonly catalog: readonly CatalogModel[];
81
+ readonly routing: ModelRoutingSettings;
82
+ readonly projectPolicy?: ProjectModelPolicy | null;
83
+ readonly taskOverride?: RoleSetting | null;
84
+ readonly requestPreference?: {
85
+ readonly modelProviderId: string;
86
+ readonly reason?: string;
87
+ } | null;
88
+ readonly workerModel?: {
89
+ readonly family?: string;
90
+ readonly providerId?: string;
91
+ readonly modelProviderId?: string;
92
+ } | null;
93
+ readonly taskRequiresVision?: boolean;
94
+ readonly requiredContextTokens?: number;
95
+ }
96
+ /**
97
+ * Pick one model for a role. The first configured layer wins.
98
+ * Capability and project scope filter that layer; they do not silently fall through.
99
+ */
100
+ export declare function resolveRoleModel(input: RoleModelRequest): ModelResolution;
@@ -0,0 +1,216 @@
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
+ */
5
+ const EXPLORER_MIN_CONTEXT = 8_000;
6
+ function roleNeeds(input) {
7
+ const context = input.requiredContextTokens ?? 0;
8
+ switch (input.role) {
9
+ case 'project_agent':
10
+ return { tools: true, vision: false, structured: false, minContext: 0 };
11
+ case 'session_worker':
12
+ return { tools: true, vision: input.taskRequiresVision === true, structured: false, minContext: 0 };
13
+ case 'explorer':
14
+ return { tools: true, vision: false, structured: false, minContext: Math.max(context, EXPLORER_MIN_CONTEXT) };
15
+ case 'verifier':
16
+ return { tools: true, vision: false, structured: false, minContext: 0 };
17
+ case 'visual_verifier':
18
+ return { tools: false, vision: true, structured: false, minContext: 0 };
19
+ case 'memory_curator':
20
+ return { tools: false, vision: false, structured: true, minContext: 0 };
21
+ case 'objective_probe':
22
+ return { tools: true, vision: false, structured: false, minContext: 0 };
23
+ case 'compactor':
24
+ return { tools: false, vision: false, structured: false, minContext: Math.max(context, 1) };
25
+ default:
26
+ return { tools: false, vision: false, structured: false, minContext: 0 };
27
+ }
28
+ }
29
+ function meetsCapability(model, needs) {
30
+ if (needs.tools && model.tools !== true)
31
+ return false;
32
+ if (needs.vision && model.vision !== true)
33
+ return false;
34
+ if (needs.structured && model.structured !== true)
35
+ return false;
36
+ if (needs.minContext > 0 && (model.contextTokens ?? 0) < needs.minContext)
37
+ return false;
38
+ return true;
39
+ }
40
+ function inScope(model, policy) {
41
+ const scope = policy?.scope;
42
+ if (!scope)
43
+ return true;
44
+ if (scope.modelProviderIds && scope.modelProviderIds.length > 0 && !scope.modelProviderIds.includes(model.modelProviderId)) {
45
+ return false;
46
+ }
47
+ if (scope.families && scope.families.length > 0 && !scope.families.includes(model.family))
48
+ return false;
49
+ if (scope.localOnly === true && model.local !== true)
50
+ return false;
51
+ return true;
52
+ }
53
+ function missingText(input, reason) {
54
+ if (reason === 'auto_pool')
55
+ return '所选模型不在自动池内';
56
+ const localOnly = input.projectPolicy?.scope?.localOnly === true;
57
+ if (input.role === 'visual_verifier') {
58
+ if (localOnly)
59
+ return '本项目只允许本地模型,但没有能看图的本地模型';
60
+ if (reason === 'scope')
61
+ return '本项目的模型范围里没有能看图的模型';
62
+ if (reason === 'empty')
63
+ return '没有可用的模型';
64
+ return '没有能看图的模型';
65
+ }
66
+ if (reason === 'scope')
67
+ return '本项目的模型范围里没有满足该角色要求的模型';
68
+ if (reason === 'capability')
69
+ return '没有满足该角色能力要求的模型';
70
+ return '没有可用的模型';
71
+ }
72
+ function expandSetting(setting, routing) {
73
+ if (setting.mode === 'fixed')
74
+ return setting.modelProviderId ? [setting.modelProviderId] : [];
75
+ if (setting.mode === 'auto')
76
+ return setting.pool.filter((id) => typeof id === 'string' && id.trim());
77
+ const binding = routing.tiers[setting.tier];
78
+ if (!binding)
79
+ return [];
80
+ return [binding.primary, ...(binding.fallbacks ?? [])].filter((id) => typeof id === 'string' && id.trim());
81
+ }
82
+ function sameFamily(model, worker) {
83
+ if (!worker)
84
+ return false;
85
+ if (worker.family)
86
+ return model.family === worker.family;
87
+ if (worker.providerId)
88
+ return model.providerId === worker.providerId;
89
+ if (worker.modelProviderId)
90
+ return model.modelProviderId === worker.modelProviderId;
91
+ return false;
92
+ }
93
+ function orderCandidates(models, input) {
94
+ if (input.role !== 'verifier' || input.routing.verifierPreferDifferentFamily !== true)
95
+ return [...models];
96
+ const different = models.filter((model) => !sameFamily(model, input.workerModel));
97
+ const same = models.filter((model) => sameFamily(model, input.workerModel));
98
+ return [...different, ...same];
99
+ }
100
+ function toSelection(model) {
101
+ return {
102
+ providerId: model.providerId,
103
+ modelId: model.modelId,
104
+ modelProviderId: model.modelProviderId,
105
+ family: model.family,
106
+ ...(model.reasoningEffort ? { reasoningEffort: model.reasoningEffort } : {}),
107
+ };
108
+ }
109
+ /** The auto pool that constrains a this-request pick. A fixed or tier override above it does not. */
110
+ function constrainingAutoPool(input) {
111
+ if (input.taskOverride?.mode === 'fixed' || input.taskOverride?.mode === 'tier')
112
+ return null;
113
+ if (input.taskOverride?.mode === 'auto')
114
+ return input.taskOverride.pool;
115
+ const projectOverride = input.projectPolicy?.overrides?.[input.role];
116
+ if (projectOverride?.mode === 'fixed' || projectOverride?.mode === 'tier')
117
+ return null;
118
+ if (projectOverride?.mode === 'auto')
119
+ return projectOverride.pool;
120
+ const globalSetting = input.routing.roles[input.role];
121
+ if (globalSetting?.mode === 'auto')
122
+ return globalSetting.pool;
123
+ return null;
124
+ }
125
+ function layersOf(input) {
126
+ const layers = [];
127
+ const requestedId = input.requestPreference?.modelProviderId;
128
+ const autoPool = constrainingAutoPool(input);
129
+ if (requestedId && autoPool) {
130
+ layers.push({
131
+ source: 'auto',
132
+ setting: { mode: 'auto', pool: autoPool },
133
+ requestedId,
134
+ });
135
+ }
136
+ else if (requestedId) {
137
+ layers.push({
138
+ source: 'this_request',
139
+ setting: { mode: 'fixed', modelProviderId: requestedId },
140
+ requestedId,
141
+ });
142
+ }
143
+ if (!requestedId) {
144
+ if (input.taskOverride)
145
+ layers.push({ source: 'task', setting: input.taskOverride });
146
+ const projectOverride = input.projectPolicy?.overrides?.[input.role];
147
+ if (projectOverride)
148
+ layers.push({ source: 'project', setting: projectOverride });
149
+ const globalSetting = input.routing.roles[input.role];
150
+ if (globalSetting)
151
+ layers.push({ source: 'global', setting: globalSetting });
152
+ }
153
+ return layers;
154
+ }
155
+ function fail(input, reason) {
156
+ return { ok: false, reason, missing: missingText(input, reason) };
157
+ }
158
+ /**
159
+ * Pick one model for a role. The first configured layer wins.
160
+ * Capability and project scope filter that layer; they do not silently fall through.
161
+ */
162
+ export function resolveRoleModel(input) {
163
+ const catalog = new Map(input.catalog.map((model) => [model.modelProviderId, model]));
164
+ const needs = roleNeeds(input);
165
+ const layers = layersOf(input);
166
+ if (layers.length === 0)
167
+ return fail(input, 'empty');
168
+ for (const layer of layers) {
169
+ if (layer.setting.mode === 'auto' && layer.requestedId && !layer.setting.pool.includes(layer.requestedId)) {
170
+ return fail(input, 'auto_pool');
171
+ }
172
+ const ids = layer.setting.mode === 'auto' && layer.requestedId
173
+ ? [layer.requestedId]
174
+ : expandSetting(layer.setting, input.routing);
175
+ if (ids.length === 0)
176
+ continue;
177
+ const models = ids
178
+ .map((id) => catalog.get(id))
179
+ .filter((model) => Boolean(model));
180
+ const eligible = [];
181
+ let layerScopeReject = false;
182
+ let layerCapabilityReject = false;
183
+ for (const model of models) {
184
+ if (!inScope(model, input.projectPolicy)) {
185
+ layerScopeReject = true;
186
+ continue;
187
+ }
188
+ if (!meetsCapability(model, needs)) {
189
+ layerCapabilityReject = true;
190
+ continue;
191
+ }
192
+ eligible.push(model);
193
+ }
194
+ if (eligible.length === 0) {
195
+ if (layerScopeReject && !layerCapabilityReject)
196
+ return fail(input, 'scope');
197
+ if (layerCapabilityReject)
198
+ return fail(input, 'capability');
199
+ return fail(input, 'empty');
200
+ }
201
+ const ordered = orderCandidates(eligible, input);
202
+ const chosen = ordered[0];
203
+ if (!chosen)
204
+ return fail(input, 'empty');
205
+ const source = layer.setting.mode === 'auto' ? 'auto' : layer.source;
206
+ return {
207
+ ok: true,
208
+ selection: toSelection(chosen),
209
+ source,
210
+ ...(input.role === 'verifier'
211
+ ? { sameFamilyAsWorker: sameFamily(chosen, input.workerModel) }
212
+ : {}),
213
+ };
214
+ }
215
+ return fail(input, 'empty');
216
+ }
@@ -0,0 +1,41 @@
1
+ /** Project objectives and watch observations. Types only, plus digest comparison. */
2
+ export type ObjectiveAutonomy = 'report_only' | 'propose' | 'act';
3
+ export type WatchTrigger = 'schedule' | 'git' | 'file' | 'ci';
4
+ export type ObjectiveStatus = 'active' | 'paused' | 'achieved' | 'abandoned';
5
+ export interface ObjectiveWatch {
6
+ readonly watchId: string;
7
+ readonly trigger: WatchTrigger;
8
+ readonly schedule?: string;
9
+ readonly ref?: string;
10
+ readonly paths?: readonly string[];
11
+ }
12
+ export interface ProjectObjective {
13
+ readonly objectiveId: string;
14
+ readonly workspaceId: string;
15
+ readonly projectAgentConversationId: string;
16
+ readonly originMessageId: string;
17
+ readonly title: string;
18
+ readonly outcome: string;
19
+ readonly autonomy: ObjectiveAutonomy;
20
+ readonly watches: readonly ObjectiveWatch[];
21
+ readonly status: ObjectiveStatus;
22
+ readonly createdBy: 'user_request' | 'agent_proposal';
23
+ readonly deadline?: string;
24
+ readonly createdAt: string;
25
+ readonly updatedAt: string;
26
+ }
27
+ export type WatchSeverity = 'info' | 'notable' | 'urgent';
28
+ export interface WatchObservation {
29
+ readonly objectiveId: string;
30
+ readonly watchId: string;
31
+ readonly observedAt: string;
32
+ readonly digest: string;
33
+ readonly summary: string;
34
+ readonly evidenceRefs: readonly string[];
35
+ readonly severity: WatchSeverity;
36
+ readonly changed: boolean;
37
+ }
38
+ /** A watch reports upward only when its digest changes. The first observation counts as a change. */
39
+ export declare function diffWatchObservation(prev: WatchObservation | null | undefined, next: Omit<WatchObservation, 'changed'> & {
40
+ readonly changed?: boolean;
41
+ }): WatchObservation;
@@ -0,0 +1,15 @@
1
+ /** Project objectives and watch observations. Types only, plus digest comparison. */
2
+ /** A watch reports upward only when its digest changes. The first observation counts as a change. */
3
+ export function diffWatchObservation(prev, next) {
4
+ const changed = !prev || prev.digest !== next.digest;
5
+ return {
6
+ objectiveId: next.objectiveId,
7
+ watchId: next.watchId,
8
+ observedAt: next.observedAt,
9
+ digest: next.digest,
10
+ summary: next.summary,
11
+ evidenceRefs: next.evidenceRefs,
12
+ severity: next.severity,
13
+ changed,
14
+ };
15
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Bot list projection. Sort is recent activity only.
3
+ * needsYou changes the badge and the filter, not the order.
4
+ */
5
+ import type { PendingApprovalState, WorkSessionStatus } from './delegation.ts';
6
+ export interface ProjectRegistryEntry {
7
+ readonly workspaceId: string;
8
+ readonly path: string;
9
+ readonly realPath: string;
10
+ readonly createdAt: string;
11
+ readonly previousPaths: readonly string[];
12
+ readonly remoteAlias?: string;
13
+ }
14
+ export type BotAvatar = {
15
+ readonly kind: 'generated';
16
+ readonly shape: string;
17
+ readonly color: string;
18
+ } | {
19
+ readonly kind: 'image';
20
+ readonly ref: string;
21
+ };
22
+ export interface BotProfile {
23
+ readonly workspaceId: string;
24
+ readonly displayName: string;
25
+ readonly avatar: BotAvatar;
26
+ readonly managed?: boolean;
27
+ readonly agentConversationId?: string;
28
+ readonly updatedAt?: string;
29
+ }
30
+ export interface BotRowState {
31
+ readonly needsYou: number;
32
+ readonly unread: number;
33
+ readonly running: number;
34
+ }
35
+ export interface BotListItem {
36
+ readonly workspaceId: string;
37
+ readonly profile: BotProfile;
38
+ readonly preview: string;
39
+ readonly lastActiveAt: string;
40
+ readonly state: BotRowState;
41
+ }
42
+ export interface BotListFilter {
43
+ readonly query?: string;
44
+ readonly needsYouOnly?: boolean;
45
+ }
46
+ export interface BotListSession {
47
+ readonly status: WorkSessionStatus;
48
+ readonly updatedAt?: string;
49
+ }
50
+ export interface BotListApproval {
51
+ readonly state: PendingApprovalState;
52
+ }
53
+ export interface BotListMessage {
54
+ readonly role: 'user' | 'assistant';
55
+ readonly text: string;
56
+ readonly at: string;
57
+ }
58
+ export declare const BOT_AVATAR_SHAPES: readonly ["circle", "square", "triangle", "diamond", "hex", "pill", "star", "arch"];
59
+ export declare const BOT_AVATAR_COLORS: readonly ["#2563eb", "#dc2626", "#d97706", "#059669", "#7c3aed", "#db2777", "#0891b2", "#4b5563"];
60
+ export declare function generateAvatar(workspaceId: string): BotAvatar;
61
+ export declare function projectBotListItem(input: {
62
+ readonly profile: BotProfile;
63
+ readonly lastMessage?: BotListMessage | null;
64
+ readonly sessions?: readonly BotListSession[];
65
+ readonly approvals?: readonly BotListApproval[];
66
+ readonly readCursor?: string | null;
67
+ }): BotListItem;
68
+ export declare function sortBotList(items: readonly BotListItem[]): BotListItem[];
69
+ export declare function filterBotList(items: readonly BotListItem[], filter?: BotListFilter): BotListItem[];
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Bot list projection. Sort is recent activity only.
3
+ * needsYou changes the badge and the filter, not the order.
4
+ */
5
+ export const BOT_AVATAR_SHAPES = [
6
+ 'circle',
7
+ 'square',
8
+ 'triangle',
9
+ 'diamond',
10
+ 'hex',
11
+ 'pill',
12
+ 'star',
13
+ 'arch',
14
+ ];
15
+ export const BOT_AVATAR_COLORS = [
16
+ '#2563eb',
17
+ '#dc2626',
18
+ '#d97706',
19
+ '#059669',
20
+ '#7c3aed',
21
+ '#db2777',
22
+ '#0891b2',
23
+ '#4b5563',
24
+ ];
25
+ const NEEDS_YOU_STATUSES = new Set(['waiting_user', 'result_ready']);
26
+ const RUNNING_STATUSES = new Set(['starting', 'running', 'verifying']);
27
+ function fnv1a(text) {
28
+ let hash = 0x811c9dc5;
29
+ for (let index = 0; index < text.length; index += 1) {
30
+ hash ^= text.charCodeAt(index);
31
+ hash = Math.imul(hash, 0x01000193);
32
+ }
33
+ return hash >>> 0;
34
+ }
35
+ export function generateAvatar(workspaceId) {
36
+ const hash = fnv1a(workspaceId);
37
+ const shape = BOT_AVATAR_SHAPES[hash % BOT_AVATAR_SHAPES.length] ?? BOT_AVATAR_SHAPES[0];
38
+ const color = BOT_AVATAR_COLORS[(hash >>> 16) % BOT_AVATAR_COLORS.length] ?? BOT_AVATAR_COLORS[0];
39
+ return { kind: 'generated', shape, color };
40
+ }
41
+ function latestIso(values) {
42
+ let best = '';
43
+ for (const value of values) {
44
+ if (!value)
45
+ continue;
46
+ if (!best || value > best)
47
+ best = value;
48
+ }
49
+ return best;
50
+ }
51
+ export function projectBotListItem(input) {
52
+ const sessions = input.sessions ?? [];
53
+ const approvals = input.approvals ?? [];
54
+ const openApprovals = approvals.filter((item) => item.state === 'open' || item.state === 'stale').length;
55
+ const waitingSessions = sessions.filter((item) => NEEDS_YOU_STATUSES.has(item.status)).length;
56
+ const running = sessions.filter((item) => RUNNING_STATUSES.has(item.status)).length;
57
+ const lastMessage = input.lastMessage ?? null;
58
+ const unread = lastMessage && lastMessage.role === 'assistant' && (!input.readCursor || lastMessage.at > input.readCursor)
59
+ ? 1
60
+ : 0;
61
+ return {
62
+ workspaceId: input.profile.workspaceId,
63
+ profile: input.profile,
64
+ preview: lastMessage?.text ?? '',
65
+ lastActiveAt: latestIso([
66
+ lastMessage?.at,
67
+ input.profile.updatedAt,
68
+ ...sessions.map((item) => item.updatedAt),
69
+ ]),
70
+ state: {
71
+ needsYou: openApprovals + waitingSessions,
72
+ unread,
73
+ running,
74
+ },
75
+ };
76
+ }
77
+ function activityMs(item) {
78
+ const parsed = Date.parse(item.lastActiveAt);
79
+ return Number.isFinite(parsed) ? parsed : 0;
80
+ }
81
+ export function sortBotList(items) {
82
+ return items
83
+ .map((item, index) => ({ item, index }))
84
+ .sort((left, right) => {
85
+ const byTime = activityMs(right.item) - activityMs(left.item);
86
+ if (byTime !== 0)
87
+ return byTime;
88
+ return left.index - right.index;
89
+ })
90
+ .map((entry) => entry.item);
91
+ }
92
+ export function filterBotList(items, filter = {}) {
93
+ const query = filter.query?.trim().toLowerCase() ?? '';
94
+ return items.filter((item) => {
95
+ if (filter.needsYouOnly === true && item.state.needsYou <= 0)
96
+ return false;
97
+ if (!query)
98
+ return true;
99
+ const haystack = `${item.profile.displayName}\n${item.preview}`.toLowerCase();
100
+ return haystack.includes(query);
101
+ });
102
+ }
package/dist/updater.d.ts CHANGED
@@ -14,14 +14,9 @@ export type UpdateChannel = 'beta' | 'stable';
14
14
  */
15
15
  export type UpdateChannelPreference = 'auto' | UpdateChannel;
16
16
  /** 更新流程阶段。渲染层据此切换徽标红点 / 摘要弹窗 / 下载进度 / 安装态的表达。 */
17
- export type UpdaterPhase = 'idle' | 'checking' | 'available' | 'not-available' | 'downloading' | 'downloaded'
18
- /**
19
- * mac 专用完成态:应用为 ad-hoc 签名,无法走 Squirrel 的「下载→签名校验→原子替换」
20
- * 自动安装链路,因此主进程自管下载 dmg 后停在此态,由用户在弹窗点击「打开安装包」,
21
- * 主进程 shell.openPath(dmg) 打开挂载,用户手动拖入「应用程序」覆盖安装。
22
- * 与 'downloaded'(Windows 重启安装)语义互斥。
23
- */
24
- | 'ready-to-open' | 'error';
17
+ export type UpdaterPhase = 'idle' | 'checking' | 'available' | 'not-available' | 'downloading'
18
+ /** 更新已下载,等待用户点击「安装」后退出替换并重启(mac / Windows / Linux AppImage 同一语义)。 */
19
+ | 'downloaded' | 'error';
25
20
  /** 主进程向渲染层广播的更新事件(与 auto-updater 的 onEvent 一一对应)。 */
26
21
  export interface UpdaterEvent {
27
22
  readonly type: 'checking-for-update' | 'update-available' | 'update-not-available' | 'download-progress' | 'update-downloaded' | 'error';
@@ -31,6 +26,8 @@ export interface UpdaterEvent {
31
26
  readonly percent?: number;
32
27
  /** 错误信息(error 时携带)。 */
33
28
  readonly message?: string;
29
+ /** 手动下载兜底的 Release 页面 URL(error 且已知可用版本时携带)。 */
30
+ readonly releaseUrl?: string;
34
31
  /** 更新说明 / release notes(available / downloaded 时可能携带)。 */
35
32
  readonly releaseNotes?: string;
36
33
  }
@@ -55,12 +52,7 @@ export interface UpdaterStatus {
55
52
  /** 更新说明 / release notes。 */
56
53
  readonly releaseNotes?: string;
57
54
  /**
58
- * mac 自管下载完成的安装包(dmg)本地绝对路径,仅 phase='ready-to-open' 时存在。
59
- * 渲染层据此启用「打开安装包」按钮(实际打开动作仍在主进程 shell.openPath 执行)。
60
- */
61
- readonly installerPath?: string;
62
- /**
63
- * 兜底用的 GitHub Release 页面 URL。当 mac 自管下载因资产缺失/命名漂移失败时,
55
+ * 兜底用的 GitHub Release 页面 URL。下载、签名校验或替换安装失败时,
64
56
  * 主进程置 phase='error' 并提供此链接,渲染层展示「打开 Release 页面」按钮。
65
57
  */
66
58
  readonly releaseUrl?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/protocol",
3
- "version": "0.0.17",
3
+ "version": "0.1.0-beta.1",
4
4
  "description": "Shared host-neutral protocol contracts for Peer Agent runtimes and clients.",
5
5
  "type": "module",
6
6
  "license": "MIT",