@getpaseo/server 0.13.0-beta.2 → 0.13.0

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.
@@ -9,10 +9,12 @@ import {
9
9
  toneFromUsedPct,
10
10
  usedPctOf,
11
11
  unavailable,
12
+ windowFromUsedPct,
12
13
  type UsageAccount,
13
14
  type UsageReport,
14
15
  type UsageBalance,
15
16
  type UsageScope,
17
+ type UsageWindow,
16
18
  } from "@getpaseo/plugin/server/usage";
17
19
 
18
20
  const ApiNumberSchema = z.coerce.number().finite();
@@ -60,6 +62,9 @@ const CursorUsageResponseSchema = z.object({
60
62
  bonusSpend: ApiNullableNumberSchema,
61
63
  remaining: ApiNullableNumberSchema,
62
64
  limit: ApiNullableNumberSchema,
65
+ totalPercentUsed: ApiNullableNumberSchema,
66
+ autoPercentUsed: ApiNullableNumberSchema,
67
+ apiPercentUsed: ApiNullableNumberSchema,
63
68
  })
64
69
  .nullish(),
65
70
  billingCycleStart: CursorBillingCycleTimestampSchema,
@@ -177,8 +182,29 @@ export async function fetchUsage(
177
182
 
178
183
  const resp = CursorUsageResponseSchema.parse(await res.json());
179
184
  const billingCycleEnd = parseCursorBillingCycleTimestamp(resp.billingCycleEnd);
185
+ const windows: UsageWindow[] = [];
180
186
  const balances: UsageBalance[] = [];
181
187
  if (resp.planUsage) {
188
+ // Total spend includes bonus credits; returned percentages measure quota usage.
189
+ for (const [id, label, usedPct] of [
190
+ ["plan_usage", "Total", resp.planUsage.totalPercentUsed],
191
+ ["cursor_usage", "Cursor", resp.planUsage.autoPercentUsed],
192
+ ["third_party_usage", "Third Party", resp.planUsage.apiPercentUsed],
193
+ ] as const) {
194
+ if (usedPct === null) continue;
195
+ windows.push(
196
+ windowFromUsedPct({
197
+ id,
198
+ label,
199
+ utilizationPct: usedPct,
200
+ resetsAt: billingCycleEnd,
201
+ summary: id === "plan_usage",
202
+ tone: toneFromUsedPct(usedPct),
203
+ }),
204
+ );
205
+ }
206
+ }
207
+ if (resp.planUsage && windows.length === 0) {
182
208
  const totalSpend = centsToDollars(resp.planUsage.totalSpend);
183
209
  const remaining = centsToDollars(resp.planUsage.remaining);
184
210
  const limit = centsToDollars(resp.planUsage.limit);
@@ -197,7 +223,7 @@ export async function fetchUsage(
197
223
  return {
198
224
  status: "available",
199
225
  planLabel: undefined,
200
- windows: [],
226
+ windows,
201
227
  balances,
202
228
  details: [],
203
229
  };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getpaseo/builtin-plugins",
3
- "version": "0.13.0-beta.2",
3
+ "version": "0.13.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {
@@ -5055,6 +5055,7 @@ export function convertClaudeHistoryEntry(entry, mapBlocks) {
5055
5055
  const userTaskNotificationItem = mapTaskNotificationUserContentToToolCall({
5056
5056
  content,
5057
5057
  messageId: userMessageId,
5058
+ notificationId: typeof entry.notificationId === "string" ? entry.notificationId : undefined,
5058
5059
  });
5059
5060
  if (userTaskNotificationItem) {
5060
5061
  return [userTaskNotificationItem];
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type { AgentTimelineItem } from "../../agent-sdk-types.js";
3
3
  declare const TaskNotificationEnvelopeSchema: z.ZodObject<{
4
+ notificationId: z.ZodOptional<z.ZodString>;
4
5
  messageId: z.ZodNullable<z.ZodString>;
5
6
  taskId: z.ZodNullable<z.ZodString>;
6
7
  toolUseId: z.ZodNullable<z.ZodString>;
@@ -12,6 +13,7 @@ declare const TaskNotificationEnvelopeSchema: z.ZodObject<{
12
13
  declare const MapTaskNotificationUserContentToToolCallInputSchema: z.ZodObject<{
13
14
  content: z.ZodUnknown;
14
15
  messageId: z.ZodNullable<z.ZodOptional<z.ZodString>>;
16
+ notificationId: z.ZodOptional<z.ZodString>;
15
17
  }, z.core.$strip>;
16
18
  export type TaskNotificationEnvelope = z.infer<typeof TaskNotificationEnvelopeSchema>;
17
19
  export type MapTaskNotificationUserContentToToolCallInput = z.infer<typeof MapTaskNotificationUserContentToToolCallInputSchema>;
@@ -28,6 +30,10 @@ export interface TaskNotificationSystemMessageLike {
28
30
  type TaskNotificationToolCallItem = Extract<AgentTimelineItem, {
29
31
  type: "tool_call";
30
32
  }>;
33
+ /** Normalize notification identity for one transcript traversal. Queue bookkeeping and delivery
34
+ * are separate records of the same occurrence; each source counts repeated identical bodies
35
+ * independently so the second event is not merged with the first. */
36
+ export declare function assignTaskNotificationReplayIds<T>(entries: Iterable<T>): Generator<T>;
31
37
  export declare function isTaskNotificationUserContent(content: unknown): boolean;
32
38
  export declare function mapTaskNotificationUserContentToToolCall(input: MapTaskNotificationUserContentToToolCallInput): TaskNotificationToolCallItem | null;
33
39
  export declare function mapTaskNotificationSystemRecordToToolCall(record: unknown): TaskNotificationToolCallItem | null;
@@ -4,6 +4,7 @@ const TASK_NOTIFICATION_MARKER = "<task-notification>";
4
4
  const TAG_NAME_PATTERN = /[.*+?^${}()|[\]\\]/g;
5
5
  const OptionalNonEmptyTrimmedStringSchema = z.preprocess((value) => (typeof value === "string" ? value.trim() : value), z.string().min(1).optional());
6
6
  const TaskNotificationEnvelopeSchema = z.object({
7
+ notificationId: z.string().optional(),
7
8
  messageId: z.string().nullable(),
8
9
  taskId: z.string().nullable(),
9
10
  toolUseId: z.string().nullable(),
@@ -24,7 +25,9 @@ const TaskNotificationUserContentSchema = z.union([
24
25
  ]);
25
26
  const TaskNotificationHistoryRecordSchema = z
26
27
  .object({
28
+ notificationId: z.string().optional(),
27
29
  type: z.string().optional(),
30
+ operation: z.string().optional(),
28
31
  subtype: z.string().optional(),
29
32
  uuid: z.string().optional(),
30
33
  message_id: z.string().optional(),
@@ -40,6 +43,7 @@ const TaskNotificationHistoryRecordSchema = z
40
43
  const MapTaskNotificationUserContentToToolCallInputSchema = z.object({
41
44
  content: z.unknown(),
42
45
  messageId: z.string().optional().nullable(),
46
+ notificationId: z.string().optional(),
43
47
  });
44
48
  function toNonEmptyString(value) {
45
49
  const parsed = OptionalNonEmptyTrimmedStringSchema.safeParse(value);
@@ -96,6 +100,7 @@ function parseTaskNotificationFromUserContent(input) {
96
100
  return null;
97
101
  }
98
102
  return TaskNotificationEnvelopeSchema.parse({
103
+ notificationId: parsedInput.data.notificationId,
99
104
  messageId: toNonEmptyString(parsedInput.data.messageId),
100
105
  taskId: readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }),
101
106
  toolUseId: readTaskNotificationTagValue({ text: rawText, tagName: "tool-use-id" }) ??
@@ -120,6 +125,7 @@ function parseTaskNotificationFromSystemRecord(record) {
120
125
  }
121
126
  const rawText = toNonEmptyString(systemRecord.content);
122
127
  return TaskNotificationEnvelopeSchema.parse({
128
+ notificationId: systemRecord.notificationId,
123
129
  messageId: toNonEmptyString(systemRecord.uuid) ?? toNonEmptyString(systemRecord.message_id),
124
130
  taskId: toNonEmptyString(systemRecord.task_id) ??
125
131
  (rawText ? readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }) : null),
@@ -140,23 +146,69 @@ function parseTaskNotificationFromSystemRecord(record) {
140
146
  rawText,
141
147
  });
142
148
  }
149
+ /** Normalize notification identity for one transcript traversal. Queue bookkeeping and delivery
150
+ * are separate records of the same occurrence; each source counts repeated identical bodies
151
+ * independently so the second event is not merged with the first. */
152
+ export function* assignTaskNotificationReplayIds(entries) {
153
+ const occurrences = new Map();
154
+ for (const entry of entries) {
155
+ const record = TaskNotificationHistoryRecordSchema.safeParse(entry);
156
+ if (!record.success) {
157
+ yield entry;
158
+ continue;
159
+ }
160
+ const data = record.data;
161
+ const envelope = data.type === "user"
162
+ ? parseTaskNotificationFromUserContent({ content: data.message?.content })
163
+ : parseTaskNotificationFromSystemRecord(data);
164
+ if (!envelope?.taskId || !data.type) {
165
+ yield entry;
166
+ continue;
167
+ }
168
+ const signature = taskNotificationReplaySignature(envelope);
169
+ const source = data.type === "queue-operation" ? `queue-${data.operation}` : data.type;
170
+ const counts = occurrences.get(signature) ?? new Map();
171
+ const occurrence = (counts.get(source) ?? 0) + 1;
172
+ counts.set(source, occurrence);
173
+ occurrences.set(signature, counts);
174
+ yield { ...entry, notificationId: `task_notification_${signature}_${occurrence}` };
175
+ }
176
+ }
177
+ function taskNotificationReplaySignature(envelope) {
178
+ // Known fields are canonical across XML user/queue records and structured system records.
179
+ // Keep the remaining body too: Monitor events share a summary but carry different <event>s.
180
+ const remainder = (envelope.rawText ?? "")
181
+ .replace(/<\/?task-notification>/gi, "")
182
+ .replace(/<(task-id|tool-use-id|tool_use_id|status|summary|output-file|output_file)>[\s\S]*?<\/\1>/gi, "")
183
+ .trim();
184
+ return createHash("sha1")
185
+ .update(JSON.stringify([
186
+ envelope.taskId,
187
+ envelope.toolUseId,
188
+ envelope.status,
189
+ envelope.summary,
190
+ envelope.outputFile,
191
+ remainder,
192
+ ]))
193
+ .digest("hex");
194
+ }
143
195
  function normalizeTaskNotificationCallIdSegment(segment) {
144
196
  const normalized = segment.trim().replace(/[^a-zA-Z0-9._:-]+/g, "_");
145
197
  return normalized.length > 0 ? normalized : null;
146
198
  }
147
199
  function buildTaskNotificationCallId(envelope) {
200
+ if (envelope.notificationId)
201
+ return envelope.notificationId;
148
202
  const messageSegment = envelope.messageId
149
203
  ? normalizeTaskNotificationCallIdSegment(envelope.messageId)
150
204
  : null;
151
- if (messageSegment) {
205
+ if (messageSegment)
152
206
  return `task_notification_${messageSegment}`;
153
- }
154
207
  const taskSegment = envelope.taskId
155
208
  ? normalizeTaskNotificationCallIdSegment(envelope.taskId)
156
209
  : null;
157
- if (taskSegment) {
210
+ if (taskSegment)
158
211
  return `task_notification_${taskSegment}`;
159
- }
160
212
  const seed = [envelope.status, envelope.summary, envelope.outputFile, envelope.rawText]
161
213
  .filter((value) => typeof value === "string")
162
214
  .join("|") || "task_notification";
@@ -1,3 +1,4 @@
1
+ import { assignTaskNotificationReplayIds } from "./task-notification-tool-call.js";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import { normalizeProviderReplayTimestamp } from "../../provider-history-timestamps.js";
@@ -64,22 +65,25 @@ function* locatedRecords(file, fd) {
64
65
  function indexedRecords(locations, descriptors) {
65
66
  return {
66
67
  *[Symbol.iterator]() {
67
- for (const location of locations) {
68
- const fd = descriptors.get(location.file);
69
- const buffer = Buffer.allocUnsafe(location.length);
70
- let read = 0;
71
- while (read < buffer.length) {
72
- const count = fs.readSync(fd, buffer, read, buffer.length - read, location.offset + read);
73
- if (count === 0)
74
- throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
75
- read += count;
76
- }
77
- const entry = parseRecord(buffer.toString("utf8"));
78
- if (entry)
79
- yield entry;
80
- }
68
+ yield* assignTaskNotificationReplayIds(readEntries());
81
69
  },
82
70
  };
71
+ function* readEntries() {
72
+ for (const location of locations) {
73
+ const fd = descriptors.get(location.file);
74
+ const buffer = Buffer.allocUnsafe(location.length);
75
+ let read = 0;
76
+ while (read < buffer.length) {
77
+ const count = fs.readSync(fd, buffer, read, buffer.length - read, location.offset + read);
78
+ if (count === 0)
79
+ throw new Error(`Claude transcript was truncated during replay: ${location.file}`);
80
+ read += count;
81
+ }
82
+ const entry = parseRecord(buffer.toString("utf8"));
83
+ if (entry)
84
+ yield entry;
85
+ }
86
+ }
83
87
  }
84
88
  function isToolResult(entry) {
85
89
  return (Array.isArray(entry.message?.content) &&
@@ -1,4 +1,5 @@
1
1
  import { OpenAI } from "openai";
2
+ import { Readable } from "node:stream";
2
3
  export class OpenAITTS {
3
4
  constructor(ttsConfig, parentLogger) {
4
5
  this.config = {
@@ -30,7 +31,9 @@ export class OpenAITTS {
30
31
  input: text,
31
32
  response_format: this.config.responseFormat,
32
33
  });
33
- const audioStream = response.body;
34
+ // Prefetched speech can wait through playback of an earlier sentence. Consume
35
+ // the response here so fetch cannot collect it and cancel its unread body.
36
+ const audioStream = Readable.from([Buffer.from(await response.arrayBuffer())]);
34
37
  const duration = Date.now() - startTime;
35
38
  this.logger.debug({ duration }, "Speech synthesis stream ready");
36
39
  return {