bb-plugin-goal 0.0.0-stage → 0.1.3

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/src/domain.ts ADDED
@@ -0,0 +1,407 @@
1
+ import { Schema } from "effect";
2
+
3
+ export const goalStates = [
4
+ "active",
5
+ "paused",
6
+ "waiting",
7
+ "completed",
8
+ "blocked",
9
+ "canceled",
10
+ ] as const;
11
+
12
+ export type GoalState = (typeof goalStates)[number];
13
+
14
+ export const goalMutationTypes = ["edit", "pause", "resume", "cancel"] as const;
15
+ export type GoalMutationType = (typeof goalMutationTypes)[number];
16
+
17
+ export const goalPauseReasonCodes = [
18
+ "manual",
19
+ "archived",
20
+ "failure",
21
+ "usage-limit",
22
+ "no-progress",
23
+ ] as const;
24
+ export type GoalPauseReasonCode = (typeof goalPauseReasonCodes)[number];
25
+
26
+ export const goalUsageLimitKinds = [
27
+ "subscription-window",
28
+ "credits",
29
+ "spend-control",
30
+ "unknown",
31
+ ] as const;
32
+ export type GoalUsageLimitKind = (typeof goalUsageLimitKinds)[number];
33
+
34
+ export const goalProgressSignalKinds = [
35
+ "tool-call",
36
+ "file-mutation",
37
+ "external-action",
38
+ "pending-interaction",
39
+ "changed-assistant-result",
40
+ ] as const;
41
+ export type GoalProgressSignalKind = (typeof goalProgressSignalKinds)[number];
42
+
43
+ export interface GoalNoProgressEvidence {
44
+ readonly continuationId: string;
45
+ readonly requestEventId: string;
46
+ readonly requestSeq: number;
47
+ readonly requestId: string;
48
+ readonly acceptedEventId: string;
49
+ readonly acceptedSeq: number;
50
+ readonly turnId: string;
51
+ readonly terminalEventId: string;
52
+ readonly terminalSeq: number;
53
+ readonly signals: GoalProgressSignalKind[];
54
+ readonly assistantResultFingerprint: string | null;
55
+ readonly previousAssistantResultFingerprint: string | null;
56
+ readonly assessment: "progress" | "no-progress";
57
+ readonly observedAt: string;
58
+ }
59
+
60
+ const GoalNoProgressEvidenceSchema = Schema.Struct({
61
+ continuationId: Schema.String,
62
+ requestEventId: Schema.String,
63
+ requestSeq: Schema.Int,
64
+ requestId: Schema.String,
65
+ acceptedEventId: Schema.String,
66
+ acceptedSeq: Schema.Int,
67
+ turnId: Schema.String,
68
+ terminalEventId: Schema.String,
69
+ terminalSeq: Schema.Int,
70
+ signals: Schema.Array(Schema.Literals(goalProgressSignalKinds)),
71
+ assistantResultFingerprint: Schema.NullOr(Schema.String),
72
+ previousAssistantResultFingerprint: Schema.NullOr(Schema.String),
73
+ assessment: Schema.Literals(["progress", "no-progress"]),
74
+ observedAt: Schema.String,
75
+ });
76
+
77
+ export const goalGuardedActionTypes = [
78
+ ...goalMutationTypes,
79
+ "complete",
80
+ "block",
81
+ ] as const;
82
+ export type GoalGuardedAction = (typeof goalGuardedActionTypes)[number];
83
+
84
+ export const GOAL_HISTORY_DEFAULT_LIMIT = 20;
85
+ export const GOAL_HISTORY_MAX_LIMIT = 100;
86
+
87
+ export const GoalDtoSchema = Schema.Struct({
88
+ id: Schema.String,
89
+ threadId: Schema.String,
90
+ objective: Schema.String,
91
+ state: Schema.Literals(goalStates),
92
+ revision: Schema.Int,
93
+ createdAt: Schema.String,
94
+ updatedAt: Schema.String,
95
+ finishedAt: Schema.NullOr(Schema.String),
96
+ completionSummary: Schema.NullOr(Schema.String),
97
+ verificationEvidence: Schema.NullOr(Schema.String),
98
+ blockageExternalAction: Schema.NullOr(Schema.String),
99
+ blockageEvidence: Schema.NullOr(Schema.String),
100
+ blockageRepeatedTurns: Schema.NullOr(Schema.Int),
101
+ pauseReasonCode: Schema.NullOr(Schema.Literals(goalPauseReasonCodes)),
102
+ pauseReason: Schema.NullOr(Schema.String),
103
+ usageLimitKind: Schema.NullOr(Schema.Literals(goalUsageLimitKinds)),
104
+ usageResetAt: Schema.NullOr(Schema.String),
105
+ noProgressConsecutiveCount: Schema.Int,
106
+ noProgressLastContinuationId: Schema.NullOr(Schema.String),
107
+ noProgressAssistantResultFingerprint: Schema.NullOr(Schema.String),
108
+ noProgressEvidence: Schema.NullOr(GoalNoProgressEvidenceSchema),
109
+ });
110
+
111
+ export interface GoalDto {
112
+ readonly id: string;
113
+ readonly threadId: string;
114
+ readonly objective: string;
115
+ readonly state: GoalState;
116
+ readonly revision: number;
117
+ readonly createdAt: string;
118
+ readonly updatedAt: string;
119
+ readonly finishedAt: string | null;
120
+ readonly completionSummary: string | null;
121
+ readonly verificationEvidence: string | null;
122
+ readonly blockageExternalAction: string | null;
123
+ readonly blockageEvidence: string | null;
124
+ readonly blockageRepeatedTurns: number | null;
125
+ readonly pauseReasonCode: GoalPauseReasonCode | null;
126
+ readonly pauseReason: string | null;
127
+ readonly usageLimitKind: GoalUsageLimitKind | null;
128
+ readonly usageResetAt: string | null;
129
+ readonly noProgressConsecutiveCount: number;
130
+ readonly noProgressLastContinuationId: string | null;
131
+ readonly noProgressAssistantResultFingerprint: string | null;
132
+ readonly noProgressEvidence: GoalNoProgressEvidence | null;
133
+ }
134
+
135
+ export interface GoalHistoryPage {
136
+ readonly goals: readonly GoalDto[];
137
+ readonly nextCursor: string | null;
138
+ }
139
+
140
+ interface GuardedGoalCommand {
141
+ readonly threadId: string;
142
+ readonly goalId: string;
143
+ readonly expectedRevision: number;
144
+ }
145
+
146
+ export interface GoalFailureEventIdentity {
147
+ readonly id: string;
148
+ readonly seq: number | null;
149
+ readonly createdAt: number;
150
+ readonly turnId?: string | null;
151
+ }
152
+
153
+ export type GoalFailure =
154
+ | {
155
+ readonly kind: "ordinary";
156
+ readonly source: "provider" | "turn" | "plugin";
157
+ readonly reason: string;
158
+ }
159
+ | {
160
+ readonly kind: "usage-limit";
161
+ readonly limitKind: GoalUsageLimitKind;
162
+ readonly reason: string;
163
+ readonly resetAt: string | null;
164
+ };
165
+
166
+ export type GoalCommand =
167
+ | {
168
+ readonly type: "start";
169
+ readonly threadId: string;
170
+ readonly objective: string;
171
+ }
172
+ | {
173
+ readonly type: "failure";
174
+ readonly threadId: string;
175
+ readonly failure: GoalFailure;
176
+ readonly event?: GoalFailureEventIdentity;
177
+ readonly observedEvents?: readonly GoalFailureEventIdentity[];
178
+ }
179
+ | {
180
+ readonly type: "status";
181
+ readonly threadId: string;
182
+ }
183
+ | {
184
+ readonly type: "history";
185
+ readonly threadId: string;
186
+ readonly limit: number;
187
+ readonly cursor: string | null;
188
+ }
189
+ | {
190
+ readonly type: "show";
191
+ readonly goalId: string;
192
+ }
193
+ | (GuardedGoalCommand & {
194
+ readonly type: "edit";
195
+ readonly objective: string;
196
+ })
197
+ | (GuardedGoalCommand & {
198
+ readonly type: "pause" | "resume" | "cancel";
199
+ })
200
+ | (GuardedGoalCommand & {
201
+ readonly type: "complete";
202
+ readonly summary: string;
203
+ readonly verificationEvidence: string;
204
+ })
205
+ | (GuardedGoalCommand & {
206
+ readonly type: "block";
207
+ readonly externalAction: string;
208
+ readonly evidence: string;
209
+ readonly repeatedTurns: number;
210
+ })
211
+ | (GuardedGoalCommand & {
212
+ readonly type: "delete";
213
+ });
214
+
215
+ export type GoalMutationCommand = Extract<
216
+ GoalCommand,
217
+ { readonly type: GoalMutationType }
218
+ >;
219
+
220
+ export type GoalCompletionCommand = Extract<
221
+ GoalCommand,
222
+ { readonly type: "complete" }
223
+ >;
224
+
225
+ export type GoalBlockedCommand = Extract<
226
+ GoalCommand,
227
+ { readonly type: "block" }
228
+ >;
229
+
230
+ export class GoalAlreadyExists extends Schema.TaggedError<GoalAlreadyExists>()(
231
+ "GoalAlreadyExists",
232
+ {
233
+ threadId: Schema.String,
234
+ goalId: Schema.String,
235
+ },
236
+ ) {}
237
+
238
+ export class GoalNotFound extends Schema.TaggedError<GoalNotFound>()(
239
+ "GoalNotFound",
240
+ {
241
+ threadId: Schema.String,
242
+ goalId: Schema.String,
243
+ },
244
+ ) {}
245
+
246
+ export class GoalStaleGuard extends Schema.TaggedError<GoalStaleGuard>()(
247
+ "GoalStaleGuard",
248
+ {
249
+ goalId: Schema.String,
250
+ expectedRevision: Schema.Int,
251
+ actualRevision: Schema.Int,
252
+ },
253
+ ) {}
254
+
255
+ export class GoalInvalidTransition extends Schema.TaggedError<GoalInvalidTransition>()(
256
+ "GoalInvalidTransition",
257
+ {
258
+ goalId: Schema.String,
259
+ action: Schema.Literals(goalGuardedActionTypes),
260
+ state: Schema.Literals(goalStates),
261
+ },
262
+ ) {}
263
+
264
+ export class GoalThreadNotFound extends Schema.TaggedError<GoalThreadNotFound>()(
265
+ "GoalThreadNotFound",
266
+ { threadId: Schema.String },
267
+ ) {}
268
+
269
+ export class GoalThreadArchived extends Schema.TaggedError<GoalThreadArchived>()(
270
+ "GoalThreadArchived",
271
+ { threadId: Schema.String },
272
+ ) {}
273
+
274
+ export class GoalRecordNotFound extends Schema.TaggedError<GoalRecordNotFound>()(
275
+ "GoalRecordNotFound",
276
+ { goalId: Schema.String },
277
+ ) {}
278
+
279
+ export class GoalInvalidCursor extends Schema.TaggedError<GoalInvalidCursor>()(
280
+ "GoalInvalidCursor",
281
+ { message: Schema.String },
282
+ ) {}
283
+
284
+ export class GoalInvalidHistoryQuery extends Schema.TaggedError<GoalInvalidHistoryQuery>()(
285
+ "GoalInvalidHistoryQuery",
286
+ { message: Schema.String },
287
+ ) {}
288
+
289
+ export class GoalInvalidObjective extends Schema.TaggedError<GoalInvalidObjective>()(
290
+ "GoalInvalidObjective",
291
+ { message: Schema.String },
292
+ ) {}
293
+
294
+ export class GoalInvalidCompletion extends Schema.TaggedError<GoalInvalidCompletion>()(
295
+ "GoalInvalidCompletion",
296
+ { message: Schema.String },
297
+ ) {}
298
+
299
+ export class GoalInvalidBlockage extends Schema.TaggedError<GoalInvalidBlockage>()(
300
+ "GoalInvalidBlockage",
301
+ { message: Schema.String },
302
+ ) {}
303
+
304
+ export class GoalPersistenceError extends Schema.TaggedError<GoalPersistenceError>()(
305
+ "GoalPersistenceError",
306
+ { message: Schema.String },
307
+ ) {}
308
+
309
+ export class GoalGatewayError extends Schema.TaggedError<GoalGatewayError>()(
310
+ "GoalGatewayError",
311
+ { message: Schema.String },
312
+ ) {}
313
+
314
+ export type GoalError =
315
+ | GoalAlreadyExists
316
+ | GoalNotFound
317
+ | GoalStaleGuard
318
+ | GoalInvalidTransition
319
+ | GoalThreadNotFound
320
+ | GoalThreadArchived
321
+ | GoalRecordNotFound
322
+ | GoalInvalidCursor
323
+ | GoalInvalidHistoryQuery
324
+ | GoalInvalidObjective
325
+ | GoalInvalidCompletion
326
+ | GoalInvalidBlockage
327
+ | GoalPersistenceError
328
+ | GoalGatewayError;
329
+
330
+ export type GoalErrorCode =
331
+ | "goal_already_exists"
332
+ | "goal_not_found"
333
+ | "stale_goal"
334
+ | "invalid_transition"
335
+ | "thread_not_found"
336
+ | "thread_archived"
337
+ | "invalid_cursor"
338
+ | "invalid_arguments"
339
+ | "invalid_objective"
340
+ | "invalid_completion"
341
+ | "invalid_blockage"
342
+ | "persistence_error"
343
+ | "gateway_error";
344
+
345
+ export interface GoalErrorDto {
346
+ readonly code: GoalErrorCode;
347
+ readonly message: string;
348
+ }
349
+
350
+ export type GoalCommandResult =
351
+ | { readonly ok: true; readonly goal: GoalDto | null }
352
+ | { readonly ok: true; readonly page: GoalHistoryPage }
353
+ | { readonly ok: false; readonly error: GoalErrorDto };
354
+
355
+ export function goalErrorToDto(error: GoalError): GoalErrorDto {
356
+ switch (error._tag) {
357
+ case "GoalAlreadyExists":
358
+ return {
359
+ code: "goal_already_exists",
360
+ message: `Thread ${error.threadId} already has unfinished Goal ${error.goalId}.`,
361
+ };
362
+ case "GoalNotFound":
363
+ return {
364
+ code: "goal_not_found",
365
+ message: `Goal ${error.goalId} was not found on thread ${error.threadId}.`,
366
+ };
367
+ case "GoalStaleGuard":
368
+ return {
369
+ code: "stale_goal",
370
+ message: `Goal ${error.goalId} changed from revision ${error.expectedRevision} to ${error.actualRevision}. Refresh and retry.`,
371
+ };
372
+ case "GoalInvalidTransition":
373
+ return {
374
+ code: "invalid_transition",
375
+ message: `Cannot ${error.action} Goal ${error.goalId} while it is ${error.state}.`,
376
+ };
377
+ case "GoalThreadNotFound":
378
+ return {
379
+ code: "thread_not_found",
380
+ message: `Thread ${error.threadId} was not found.`,
381
+ };
382
+ case "GoalThreadArchived":
383
+ return {
384
+ code: "thread_archived",
385
+ message: `Thread ${error.threadId} is archived. Unarchive it before starting or resuming a Goal.`,
386
+ };
387
+ case "GoalRecordNotFound":
388
+ return {
389
+ code: "goal_not_found",
390
+ message: `Goal ${error.goalId} was not found.`,
391
+ };
392
+ case "GoalInvalidCursor":
393
+ return { code: "invalid_cursor", message: error.message };
394
+ case "GoalInvalidHistoryQuery":
395
+ return { code: "invalid_arguments", message: error.message };
396
+ case "GoalInvalidObjective":
397
+ return { code: "invalid_objective", message: error.message };
398
+ case "GoalInvalidCompletion":
399
+ return { code: "invalid_completion", message: error.message };
400
+ case "GoalInvalidBlockage":
401
+ return { code: "invalid_blockage", message: error.message };
402
+ case "GoalPersistenceError":
403
+ return { code: "persistence_error", message: error.message };
404
+ case "GoalGatewayError":
405
+ return { code: "gateway_error", message: error.message };
406
+ }
407
+ }
package/src/failure.ts ADDED
@@ -0,0 +1,202 @@
1
+ import { z } from "zod";
2
+ import {
3
+ type GoalFailure,
4
+ type GoalFailureEventIdentity,
5
+ type GoalUsageLimitKind,
6
+ goalUsageLimitKinds,
7
+ } from "./domain";
8
+
9
+ export interface GoalFailureEvent extends GoalFailureEventIdentity {
10
+ readonly seq: number;
11
+ readonly type: string;
12
+ readonly data: unknown;
13
+ }
14
+
15
+ export interface ClassifiedGoalFailure {
16
+ readonly failure: GoalFailure;
17
+ readonly event: GoalFailureEventIdentity | null;
18
+ }
19
+
20
+ const terminalFailureEventTypes = new Set([
21
+ "provider/error",
22
+ "system/error",
23
+ ]);
24
+
25
+ const providerErrorData = z
26
+ .object({
27
+ message: z.string().optional(),
28
+ willRetry: z.boolean().optional(),
29
+ errorInfo: z
30
+ .object({
31
+ category: z.string(),
32
+ providerCode: z.string().nullable().optional(),
33
+ })
34
+ .optional(),
35
+ })
36
+ .passthrough();
37
+
38
+ const rateLimitsData = z
39
+ .object({
40
+ rateLimits: z
41
+ .object({
42
+ kind: z.enum(goalUsageLimitKinds),
43
+ status: z.enum(["allowed", "blocked", "unknown", "warning"]),
44
+ reachedReason: z.string().nullable().optional(),
45
+ windows: z
46
+ .array(
47
+ z
48
+ .object({
49
+ status: z.enum(["allowed", "blocked", "unknown", "warning"]),
50
+ resetsAtMs: z.number().finite().nullable(),
51
+ label: z.string().nullable().optional(),
52
+ })
53
+ .passthrough(),
54
+ )
55
+ .optional(),
56
+ })
57
+ .passthrough(),
58
+ })
59
+ .passthrough();
60
+
61
+ function usageFailure(
62
+ limitKind: GoalUsageLimitKind,
63
+ reason: string,
64
+ resetAt: string | null,
65
+ ): GoalFailure {
66
+ return { kind: "usage-limit", limitKind, reason, resetAt };
67
+ }
68
+
69
+ function validResetAt(
70
+ resetsAtMs: number | null | undefined,
71
+ nowMs: number,
72
+ ): string | null {
73
+ if (resetsAtMs === null || resetsAtMs === undefined || resetsAtMs <= nowMs) {
74
+ return null;
75
+ }
76
+ const resetAt = new Date(resetsAtMs);
77
+ return Number.isNaN(resetAt.getTime()) ? null : resetAt.toISOString();
78
+ }
79
+
80
+ function latestEvent(
81
+ events: readonly GoalFailureEvent[],
82
+ predicate: (event: GoalFailureEvent) => boolean,
83
+ ): GoalFailureEvent | null {
84
+ return events.reduce<GoalFailureEvent | null>(
85
+ (latest, event) =>
86
+ predicate(event) && (latest === null || event.seq > latest.seq)
87
+ ? event
88
+ : latest,
89
+ null,
90
+ );
91
+ }
92
+
93
+ function blockedRateLimits(
94
+ event: GoalFailureEvent | null,
95
+ nowMs: number,
96
+ ): { readonly kind: GoalUsageLimitKind; readonly reason: string; readonly resetAt: string | null } | null {
97
+ if (event === null) return null;
98
+ const parsedRate = rateLimitsData.safeParse(event.data);
99
+ if (!parsedRate.success || parsedRate.data.rateLimits.status !== "blocked") {
100
+ return null;
101
+ }
102
+ const rate = parsedRate.data.rateLimits;
103
+ const blockedWindows = (rate.windows ?? []).filter(
104
+ (window) => window.status === "blocked",
105
+ );
106
+ const resetTimes = blockedWindows.map((window) => window.resetsAtMs);
107
+ const hasUntrustworthyReset = resetTimes.some((resetTime) => resetTime === null);
108
+ const trustworthyResetTimes = resetTimes.filter(
109
+ (resetTime): resetTime is number => resetTime !== null,
110
+ );
111
+ const resetAt =
112
+ blockedWindows.length === 0 || hasUntrustworthyReset
113
+ ? null
114
+ : validResetAt(Math.max(...trustworthyResetTimes), nowMs);
115
+ return {
116
+ kind: rate.kind,
117
+ reason: rate.reachedReason ?? "Provider usage limit reached.",
118
+ resetAt,
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Classify a failed run as a fact set. A terminal rate-limit error pairs with
124
+ * the latest blocked rate-limit state in the same run; the event kind alone
125
+ * is not a priority and cannot make stale history win.
126
+ */
127
+ export function classifyGoalFailureWithIdentity(
128
+ events: readonly GoalFailureEvent[],
129
+ nowMs: number,
130
+ fallbackMessage: string | null = null,
131
+ ): ClassifiedGoalFailure {
132
+ const terminal = latestEvent(events, (event) =>
133
+ terminalFailureEventTypes.has(event.type),
134
+ );
135
+ const latestRateLimits = latestEvent(
136
+ events,
137
+ (event) => event.type === "provider/rateLimits/updated",
138
+ );
139
+ const blockedRate = blockedRateLimits(latestRateLimits, nowMs);
140
+
141
+ if (terminal?.type === "provider/error") {
142
+ const parsedProvider = providerErrorData.safeParse(terminal.data);
143
+ if (parsedProvider.success) {
144
+ const info = parsedProvider.data.errorInfo;
145
+ if (info?.category === "rate-limit" && parsedProvider.data.willRetry !== true) {
146
+ return {
147
+ event: terminal,
148
+ failure:
149
+ blockedRate === null
150
+ ? usageFailure(
151
+ "unknown",
152
+ parsedProvider.data.message ?? "Provider rate limit reached.",
153
+ null,
154
+ )
155
+ : usageFailure(
156
+ blockedRate.kind,
157
+ blockedRate.reason,
158
+ blockedRate.resetAt,
159
+ ),
160
+ };
161
+ }
162
+ const category = info?.category ?? "unknown";
163
+ const code = info?.providerCode === null ? null : info?.providerCode;
164
+ return {
165
+ event: terminal,
166
+ failure: {
167
+ kind: "ordinary",
168
+ source: "provider",
169
+ reason: `Provider ${category}${code === undefined || code === null ? "" : ` (${code})`}: ${parsedProvider.data.message ?? "request failed"}`,
170
+ },
171
+ };
172
+ }
173
+ }
174
+
175
+ const systemMessage =
176
+ terminal?.type === "system/error"
177
+ ? z
178
+ .object({ message: z.string().optional() })
179
+ .passthrough()
180
+ .safeParse(terminal.data)
181
+ : null;
182
+ return {
183
+ event: terminal,
184
+ failure: {
185
+ kind: "ordinary",
186
+ source: "turn",
187
+ reason:
188
+ systemMessage?.success && systemMessage.data.message !== undefined
189
+ ? systemMessage.data.message
190
+ : fallbackMessage ?? "The Goal turn failed.",
191
+ },
192
+ };
193
+ }
194
+
195
+ /** Classify structured facts; fallback prose is display-only. */
196
+ export function classifyGoalFailure(
197
+ events: readonly GoalFailureEvent[],
198
+ nowMs: number,
199
+ fallbackMessage: string | null = null,
200
+ ): GoalFailure {
201
+ return classifyGoalFailureWithIdentity(events, nowMs, fallbackMessage).failure;
202
+ }
@@ -0,0 +1,46 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { GoalInvalidCursor } from "./domain";
3
+
4
+ const GoalHistoryCursorPayloadSchema = Schema.Struct({
5
+ version: Schema.Literals([1]),
6
+ threadId: Schema.NonEmptyString,
7
+ sequence: Schema.Int.check(Schema.isGreaterThan(0)),
8
+ });
9
+
10
+ export interface GoalHistoryBoundary {
11
+ readonly threadId: string;
12
+ readonly sequence: number;
13
+ }
14
+
15
+ const decodePayload = Schema.decodeUnknownSync(GoalHistoryCursorPayloadSchema);
16
+
17
+ export function encodeGoalHistoryCursor(
18
+ boundary: GoalHistoryBoundary,
19
+ ): string {
20
+ return Buffer.from(
21
+ JSON.stringify({ version: 1, ...boundary }),
22
+ "utf8",
23
+ ).toString("base64url");
24
+ }
25
+
26
+ export const decodeGoalHistoryCursor = Effect.fn(
27
+ "decodeGoalHistoryCursor",
28
+ )((cursor: string) =>
29
+ Effect.try({
30
+ try: (): GoalHistoryBoundary => {
31
+ const bytes = Buffer.from(cursor, "base64url");
32
+ if (bytes.length === 0 || bytes.toString("base64url") !== cursor) {
33
+ throw new Error("Cursor is not canonical base64url.");
34
+ }
35
+ const decoded = decodePayload(JSON.parse(bytes.toString("utf8")));
36
+ return {
37
+ threadId: decoded.threadId,
38
+ sequence: decoded.sequence,
39
+ };
40
+ },
41
+ catch: () =>
42
+ new GoalInvalidCursor({
43
+ message: "The Goal history cursor is invalid or expired.",
44
+ }),
45
+ }),
46
+ );