@omercnet/paseo-omp 0.4.0-next.122.1 → 0.4.0-next.124.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-omp",
3
- "version": "0.4.0-next.122.1",
3
+ "version": "0.4.0-next.124.1",
4
4
  "type": "module",
5
5
  "description": "Paseo integration for OMP, including its direct provider and workspace tooling.",
6
6
  "license": "MIT",
@@ -1,2 +1,2 @@
1
1
  /** Release Please keeps this bundle-safe constant aligned with package.json. */
2
- export const PASEO_OMP_PACKAGE_VERSION = "0.4.0-next.122.1"; // x-release-please-version
2
+ export const PASEO_OMP_PACKAGE_VERSION = "0.4.0-next.124.1"; // x-release-please-version
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ProviderEvent } from "@getpaseo/plugin/server/provider";
3
+ import type { OmpRpcEvent } from "./omp-rpc-protocol";
4
+ import type { OmpPublicDataSerializer } from "./security";
5
+ import type { ActiveTurn } from "./session-terminal";
6
+ import type { OmpSessionUsage } from "./session-usage";
7
+ import type { OmpTimelineProjector } from "./timeline-projector";
8
+
9
+ type Emit = (event: ProviderEvent) => void;
10
+
11
+ export interface ActiveCompaction {
12
+ id: string;
13
+ trigger: "auto" | "manual";
14
+ turnId: string;
15
+ generation: number;
16
+ retrying: boolean;
17
+ action?: string;
18
+ preTokens?: number;
19
+ }
20
+
21
+ export class OmpSessionCompaction {
22
+ private operation: ActiveCompaction | null = null;
23
+ private discardedEnds = 0;
24
+
25
+ constructor(
26
+ private readonly sessionId: string,
27
+ private readonly emit: Emit,
28
+ private readonly projector: OmpTimelineProjector,
29
+ private readonly dataFilter: OmpPublicDataSerializer,
30
+ private readonly usage: OmpSessionUsage,
31
+ ) {}
32
+
33
+ get active(): ActiveCompaction | null {
34
+ return this.operation;
35
+ }
36
+
37
+ start(turn: ActiveTurn, trigger: "auto" | "manual", action?: string): void {
38
+ if (this.discardedEnds > 0) {
39
+ this.discardedEnds += 1;
40
+ return;
41
+ }
42
+ const active = this.operation;
43
+ if (active && active.trigger === trigger && active.action === action) {
44
+ active.retrying = false;
45
+ return;
46
+ }
47
+ if (active) {
48
+ this.retire("OMP emitted overlapping compactions");
49
+ this.discardedEnds = 2;
50
+ return;
51
+ }
52
+ const operation: ActiveCompaction = {
53
+ id: randomUUID(),
54
+ trigger,
55
+ turnId: turn.turnId,
56
+ generation: turn.generation,
57
+ action,
58
+ retrying: false,
59
+ preTokens: this.usage.latest?.contextWindowUsedTokens,
60
+ };
61
+ this.operation = operation;
62
+ this.projector.flush(true);
63
+ this.emit({
64
+ type: "timeline.item",
65
+ sessionId: this.sessionId,
66
+ item: {
67
+ id: operation.id,
68
+ type: "compaction",
69
+ status: "loading",
70
+ trigger,
71
+ ...(operation.preTokens !== undefined ? { preTokens: operation.preTokens } : {}),
72
+ },
73
+ });
74
+ }
75
+
76
+ handleAutoEnd(
77
+ turn: ActiveTurn,
78
+ event: Extract<OmpRpcEvent, { type: "auto_compaction_end" }>,
79
+ ): boolean {
80
+ if (this.discardedEnds > 0) {
81
+ this.discardedEnds -= 1;
82
+ return false;
83
+ }
84
+ const operation = this.operation;
85
+ if (
86
+ operation?.trigger !== "auto" ||
87
+ operation.turnId !== turn.turnId ||
88
+ operation.generation !== turn.generation
89
+ ) {
90
+ return false;
91
+ }
92
+ if (event.action !== undefined && operation.action !== event.action) {
93
+ this.retire("OMP emitted overlapping compactions");
94
+ this.discardedEnds = 1;
95
+ return false;
96
+ }
97
+ if (event.willRetry) {
98
+ operation.retrying = true;
99
+ return false;
100
+ }
101
+ if (operation.retrying) {
102
+ operation.retrying = false;
103
+ return false;
104
+ }
105
+ const state = event.aborted
106
+ ? "canceled"
107
+ : event.errorMessage
108
+ ? "failed"
109
+ : event.skipped
110
+ ? "skipped"
111
+ : "completed";
112
+ this.finish(state, {
113
+ tokensBefore: event.result?.tokensBefore ?? event.result?.preTokens,
114
+ message: event.errorMessage,
115
+ });
116
+ return true;
117
+ }
118
+
119
+ finish(
120
+ state: "completed" | "failed" | "canceled" | "skipped",
121
+ options: { tokensBefore?: number | null; message?: string } = {},
122
+ ): void {
123
+ const operation = this.operation;
124
+ if (!operation) return;
125
+ this.operation = null;
126
+ this.projector.flush(true);
127
+ if (state === "completed") {
128
+ this.usage.completeCompaction();
129
+ }
130
+ if (state !== "completed") {
131
+ const defaultMessage =
132
+ state === "failed"
133
+ ? "OMP compaction failed"
134
+ : state === "canceled"
135
+ ? "OMP compaction canceled"
136
+ : "OMP compaction skipped";
137
+ this.emit({
138
+ type: "timeline.item",
139
+ sessionId: this.sessionId,
140
+ item: {
141
+ id: operation.id,
142
+ type: "notification",
143
+ level: state === "failed" ? "error" : "info",
144
+ message: this.dataFilter.text(options.message ?? defaultMessage, 4_096),
145
+ },
146
+ });
147
+ return;
148
+ }
149
+ const tokensBefore = options.tokensBefore ?? operation.preTokens;
150
+ this.emit({
151
+ type: "timeline.item",
152
+ sessionId: this.sessionId,
153
+ item: {
154
+ id: operation.id,
155
+ type: "compaction",
156
+ status: "completed",
157
+ trigger: operation.trigger,
158
+ ...(tokensBefore !== undefined ? { preTokens: tokensBefore } : {}),
159
+ },
160
+ });
161
+ }
162
+
163
+ retire(message: string): void {
164
+ const operation = this.operation;
165
+ if (!operation) return;
166
+ this.operation = null;
167
+ this.emit({
168
+ type: "timeline.item",
169
+ sessionId: this.sessionId,
170
+ item: {
171
+ id: operation.id,
172
+ type: "compaction",
173
+ status: "completed",
174
+ trigger: operation.trigger,
175
+ },
176
+ });
177
+ this.emit({
178
+ type: "timeline.item",
179
+ sessionId: this.sessionId,
180
+ item: { id: `${operation.id}:error`, type: "error", message },
181
+ });
182
+ }
183
+
184
+ resetDiscardedEnds(): void {
185
+ this.discardedEnds = 0;
186
+ }
187
+ }
@@ -0,0 +1,42 @@
1
+ import type { OmpRpcEvent } from "./omp-rpc-protocol";
2
+
3
+ export function isNativeTurnActivity(event: OmpRpcEvent): boolean {
4
+ if (
5
+ event.type === "agent_start" ||
6
+ event.type === "turn_start" ||
7
+ event.type === "turn_end" ||
8
+ event.type === "agent_end" ||
9
+ event.type === "auto_compaction_start" ||
10
+ event.type === "auto_compaction_end"
11
+ ) {
12
+ return true;
13
+ }
14
+ if (
15
+ event.type === "message_start" ||
16
+ event.type === "message_update" ||
17
+ event.type === "message_end"
18
+ ) {
19
+ return event.message.role === "assistant";
20
+ }
21
+ return event.type.startsWith("tool_execution_");
22
+ }
23
+ export function isRuntimeConfigEvent(event: OmpRpcEvent): boolean {
24
+ return (
25
+ event.type === "model_changed" ||
26
+ event.type === "thinking_level_changed" ||
27
+ event.type === "retry_fallback_applied" ||
28
+ event.type === "retry_fallback_succeeded"
29
+ );
30
+ }
31
+
32
+ export function isPassiveUiMethod(method: string): boolean {
33
+ return (
34
+ method === "cancel" ||
35
+ method === "notify" ||
36
+ method === "open_url" ||
37
+ method === "setStatus" ||
38
+ method === "setWidget" ||
39
+ method === "setTitle" ||
40
+ method === "set_editor_text"
41
+ );
42
+ }
@@ -0,0 +1,307 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { ProviderError } from "@getpaseo/plugin/server/provider";
3
+ import type { OmpMessage, OmpRpcEvent } from "./omp-rpc-protocol";
4
+
5
+ export type PendingUser = {
6
+ clientMessageId: string;
7
+ text: string;
8
+ accepted: boolean;
9
+ fallbackOnFinish: boolean;
10
+ bufferedEchoes: OmpMessage[];
11
+ };
12
+ type TerminalCorrelationEvidence = "fresh-native-user" | "current-assistant";
13
+
14
+ type TerminalCorrelation = {
15
+ policy: "initial-turn" | "ordered-legacy" | "native-command";
16
+ evidence: Map<TerminalCorrelationEvidence, number>;
17
+ };
18
+
19
+ export type TerminalCandidate = {
20
+ event: Extract<OmpRpcEvent, { type: "agent_end" }>;
21
+ arrivalSequence: number;
22
+ confidence:
23
+ | "keyed"
24
+ | "initial-turn"
25
+ | "ordered-legacy"
26
+ | "native-command"
27
+ | "interrupted"
28
+ | "ambiguous";
29
+ };
30
+
31
+ export type ActiveTurn = {
32
+ turnId: string;
33
+ clientMessageId: string;
34
+ generation: number;
35
+ promptResultEmitted: boolean;
36
+ started: boolean;
37
+ terminal: boolean;
38
+ interrupted: boolean;
39
+ starting: boolean;
40
+ nativeActivity: boolean;
41
+ userEchoObserved: boolean;
42
+ localOnlyDisabled: boolean;
43
+ localOnlyEligible: boolean;
44
+ awaitingPermissionEvidence: boolean;
45
+ activitySequence: number;
46
+ acknowledged: boolean;
47
+ terminalCorrelation: TerminalCorrelation;
48
+ replayingBufferedEvents: boolean;
49
+ agentInvoked?: boolean;
50
+ nativeRequestId?: string;
51
+ promptAcceptedEventIndex?: number;
52
+ localOnlyTimer?: unknown;
53
+ usagePollTimer?: unknown;
54
+ usagePoll?: Promise<void>;
55
+ usageSampleFloor: number;
56
+ manualCompaction: boolean;
57
+ manualCompactionPending: boolean;
58
+ manualCompactionDeadlineTimer?: unknown;
59
+ agentEndPending: boolean;
60
+ agentEndRetryTimer?: unknown;
61
+ agentEndDeadlineTimer?: unknown;
62
+ agentEndCheck?: Promise<void>;
63
+ ambiguousTerminalTimer?: unknown;
64
+ terminalizing: boolean;
65
+ terminalization?: Promise<void>;
66
+ terminalOutcome?: TurnOutcome;
67
+ operationalTerminalStage?: "failed" | "unresolved";
68
+ terminalWake?: VoidDeferred;
69
+ steerReady: VoidDeferred;
70
+ steersInFlight: number;
71
+ deferredAgentEnd?: TerminalCandidate;
72
+ activeToolCallIds: Set<string>;
73
+ bufferedEvents: OmpRpcEvent[];
74
+ pendingUsers: PendingUser[];
75
+ userEchoes: OmpMessage[];
76
+ userCorrelationActive: boolean;
77
+ userLookups: Set<Promise<void>>;
78
+ completedMessageCount: number;
79
+ streamedMessageEntryIds: string[];
80
+ streamedMessageIdentityComplete: boolean;
81
+ lastCompletedAssistantOutcome?: AgentEndOutcome;
82
+ lastCompletedAssistantEntryId?: string;
83
+ };
84
+
85
+ export type VoidDeferred = {
86
+ promise: Promise<void>;
87
+ resolve(value?: void | PromiseLike<void>): void;
88
+ reject(reason?: unknown): void;
89
+ };
90
+
91
+ export type TurnOutcome = {
92
+ state: "completed" | "failed" | "canceled";
93
+ error?: ProviderError;
94
+ usageSampled: boolean;
95
+ };
96
+
97
+ export function nativeEntryId(message: OmpMessage): string | undefined {
98
+ return message.entryId;
99
+ }
100
+
101
+ export type AgentEndOutcome = "completed" | "failed" | "canceled";
102
+ type AssistantTerminalStatus = AgentEndOutcome | "unavailable";
103
+
104
+ export function assistantTerminalOutcome(
105
+ message: Extract<OmpMessage, { role: "assistant" }>,
106
+ ): AgentEndOutcome {
107
+ const stopReason = message.stopReason?.toLowerCase();
108
+ if (stopReason === "aborted" || stopReason === "canceled" || stopReason === "cancelled") {
109
+ return "canceled";
110
+ }
111
+ return stopReason === "error" || message.errorMessage ? "failed" : "completed";
112
+ }
113
+
114
+ function lastAssistantStatus(
115
+ messages: readonly OmpMessage[],
116
+ startIndex = 0,
117
+ ): AssistantTerminalStatus {
118
+ for (let index = messages.length - 1; index >= startIndex; index -= 1) {
119
+ const message = messages[index];
120
+ if (message?.role !== "assistant") continue;
121
+ return assistantTerminalOutcome(message);
122
+ }
123
+ return "unavailable";
124
+ }
125
+
126
+ export function terminalOutcome(
127
+ event: Extract<OmpRpcEvent, { type: "agent_end" }>,
128
+ turn: Pick<ActiveTurn, "completedMessageCount" | "lastCompletedAssistantOutcome">,
129
+ ): AgentEndOutcome | undefined {
130
+ const messages = event.messages;
131
+ if (
132
+ messages !== undefined &&
133
+ (event.messageCount === undefined || messages.length >= event.messageCount)
134
+ ) {
135
+ const status = lastAssistantStatus(messages);
136
+ return status === "unavailable" ? "completed" : status;
137
+ }
138
+ if (event.messageCount === 0) return "completed";
139
+ if (
140
+ turn.lastCompletedAssistantOutcome !== undefined &&
141
+ (event.messageCount === undefined || turn.completedMessageCount >= event.messageCount)
142
+ ) {
143
+ return turn.lastCompletedAssistantOutcome;
144
+ }
145
+ return undefined;
146
+ }
147
+
148
+ export function historyTerminalOutcome(
149
+ messages: readonly OmpMessage[],
150
+ declaredCount: number,
151
+ turn: Pick<
152
+ ActiveTurn,
153
+ | "streamedMessageEntryIds"
154
+ | "streamedMessageIdentityComplete"
155
+ | "lastCompletedAssistantOutcome"
156
+ | "lastCompletedAssistantEntryId"
157
+ >,
158
+ retainedMessages: readonly OmpMessage[],
159
+ ): AgentEndOutcome | undefined {
160
+ if (
161
+ messages.length < declaredCount ||
162
+ !turn.streamedMessageIdentityComplete ||
163
+ turn.streamedMessageEntryIds.length === 0
164
+ ) {
165
+ return undefined;
166
+ }
167
+ const startIndex = messages.length - declaredCount;
168
+ let historyIndex = startIndex;
169
+ for (const entryId of turn.streamedMessageEntryIds) {
170
+ while (historyIndex < messages.length) {
171
+ const historyMessage = messages[historyIndex];
172
+ if (historyMessage && nativeEntryId(historyMessage) === entryId) break;
173
+ historyIndex += 1;
174
+ }
175
+ if (historyIndex >= messages.length) return undefined;
176
+ const correlated = messages[historyIndex];
177
+ if (
178
+ entryId === turn.lastCompletedAssistantEntryId &&
179
+ (correlated?.role !== "assistant" ||
180
+ assistantTerminalOutcome(correlated) !== turn.lastCompletedAssistantOutcome)
181
+ )
182
+ return undefined;
183
+ historyIndex += 1;
184
+ }
185
+ historyIndex = startIndex;
186
+ for (const retained of retainedMessages) {
187
+ const entryId = nativeEntryId(retained);
188
+ if (!entryId) return undefined;
189
+ while (historyIndex < messages.length) {
190
+ const historyMessage = messages[historyIndex];
191
+ if (historyMessage && nativeEntryId(historyMessage) === entryId) break;
192
+ historyIndex += 1;
193
+ }
194
+ if (historyIndex >= messages.length) return undefined;
195
+ const correlated = messages[historyIndex];
196
+ if (!correlated || correlated.role !== retained.role) return undefined;
197
+ if (
198
+ retained.role === "assistant" &&
199
+ correlated.role === "assistant" &&
200
+ assistantTerminalOutcome(retained) !== assistantTerminalOutcome(correlated)
201
+ )
202
+ return undefined;
203
+ historyIndex += 1;
204
+ }
205
+ const status = lastAssistantStatus(messages, startIndex);
206
+ return status === "unavailable" ? undefined : status;
207
+ }
208
+
209
+ export function unknownTerminalOutcomeError(
210
+ event: Extract<OmpRpcEvent, { type: "agent_end" }>,
211
+ turn: Pick<ActiveTurn, "completedMessageCount" | "lastCompletedAssistantOutcome">,
212
+ ): string {
213
+ const retainedMessages = event.messages?.length ?? 0;
214
+ const retainedStatus = event.messages ? lastAssistantStatus(event.messages) : "unavailable";
215
+ const lastStatus =
216
+ retainedStatus === "unavailable"
217
+ ? (turn.lastCompletedAssistantOutcome ?? "unavailable")
218
+ : retainedStatus;
219
+ return (
220
+ "OMP agent_end omitted terminal messages; outcome is unknown " +
221
+ `(declaredCount=${event.messageCount ?? "unavailable"}, ` +
222
+ `observedCount=${turn.completedMessageCount}, ` +
223
+ `retainedTerminalMessages=${retainedMessages}, lastAssistantStatus=${lastStatus})`
224
+ );
225
+ }
226
+
227
+ export function createActiveTurn(
228
+ clientMessageId: string,
229
+ text: string,
230
+ generation: number,
231
+ terminalPolicy: TerminalCorrelation["policy"],
232
+ manualCompaction = false,
233
+ ): ActiveTurn {
234
+ return {
235
+ turnId: randomUUID(),
236
+ clientMessageId,
237
+ agentInvoked: undefined,
238
+ generation,
239
+ promptResultEmitted: false,
240
+ started: false,
241
+ terminal: false,
242
+ awaitingPermissionEvidence: false,
243
+ interrupted: false,
244
+ starting: true,
245
+ nativeActivity: false,
246
+ userEchoObserved: false,
247
+ localOnlyDisabled: false,
248
+ localOnlyEligible: false,
249
+ usageSampleFloor: 0,
250
+ agentEndPending: false,
251
+ terminalizing: false,
252
+ manualCompactionPending: manualCompaction,
253
+ manualCompaction,
254
+ activitySequence: 0,
255
+ acknowledged: false,
256
+ terminalCorrelation: { policy: terminalPolicy, evidence: new Map() },
257
+ replayingBufferedEvents: false,
258
+ steersInFlight: 0,
259
+ activeToolCallIds: new Set(),
260
+ steerReady: Promise.withResolvers<void>(),
261
+ userCorrelationActive: false,
262
+ userLookups: new Set(),
263
+ userEchoes: [],
264
+ completedMessageCount: 0,
265
+ bufferedEvents: [],
266
+ streamedMessageEntryIds: [],
267
+ streamedMessageIdentityComplete: true,
268
+ pendingUsers: [
269
+ {
270
+ clientMessageId,
271
+ text,
272
+ accepted: true,
273
+ fallbackOnFinish: true,
274
+ bufferedEchoes: [],
275
+ },
276
+ ],
277
+ };
278
+ }
279
+ export function classifyTerminalCandidate(
280
+ turn: ActiveTurn,
281
+ event: Extract<OmpRpcEvent, { type: "agent_end" }>,
282
+ arrivalSequence = turn.activitySequence,
283
+ ): TerminalCandidate {
284
+ if (event.requestId !== undefined) return { event, confidence: "keyed", arrivalSequence };
285
+ if (turn.agentInvoked === false) return { event, confidence: "ambiguous", arrivalSequence };
286
+ if (turn.terminalCorrelation.policy === "initial-turn") {
287
+ return { event, confidence: "initial-turn", arrivalSequence };
288
+ }
289
+ const assistantSequence = turn.terminalCorrelation.evidence.get("current-assistant");
290
+ if (
291
+ turn.terminalCorrelation.policy === "native-command" &&
292
+ assistantSequence !== undefined &&
293
+ assistantSequence <= arrivalSequence
294
+ ) {
295
+ return { event, confidence: "native-command", arrivalSequence };
296
+ }
297
+ const userSequence = turn.terminalCorrelation.evidence.get("fresh-native-user");
298
+ if (
299
+ userSequence !== undefined &&
300
+ assistantSequence !== undefined &&
301
+ userSequence < assistantSequence &&
302
+ assistantSequence <= arrivalSequence
303
+ ) {
304
+ return { event, confidence: "ordered-legacy", arrivalSequence };
305
+ }
306
+ return { event, confidence: "ambiguous", arrivalSequence };
307
+ }