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/server.ts ADDED
@@ -0,0 +1,1758 @@
1
+ import { isAbsolute, resolve } from "node:path";
2
+ import type BetterSqlite3 from "better-sqlite3";
3
+ import {
4
+ defineRpcContract,
5
+ type BbPluginApi,
6
+ type PluginCliContext,
7
+ type PluginCliResult,
8
+ } from "@get-bb/plugin-sdk";
9
+ import { z } from "zod";
10
+ import {
11
+ GOAL_HISTORY_DEFAULT_LIMIT,
12
+ GOAL_HISTORY_MAX_LIMIT,
13
+ goalStates,
14
+ type GoalCommandResult,
15
+ type GoalDto,
16
+ type GoalHistoryPage,
17
+ type GoalMutationType,
18
+ } from "./src/domain";
19
+ import {
20
+ GOAL_MIGRATIONS,
21
+ makeCurrentGoalSnapshotReader,
22
+ } from "./src/repository";
23
+ import {
24
+ makeGoalRuntime,
25
+ type GoalRuntime,
26
+ } from "./src/runtime";
27
+ import type { GoalThreadGatewayAdapter } from "./src/coordinator";
28
+ import {
29
+ classifyGoalFailureWithIdentity,
30
+ type ClassifiedGoalFailure,
31
+ } from "./src/failure";
32
+ import { usageResetWaitMs } from "./src/usage-wait";
33
+ import type { GoalFailureEventIdentity } from "./src/domain";
34
+ import {
35
+ continuationPrompt,
36
+ observeSettledContinuation,
37
+ type GoalStructuredEventRow,
38
+ } from "./src/progress";
39
+
40
+ export const GOAL_REALTIME_CHANNEL = "goal.changed";
41
+
42
+ const goalSchema = z
43
+ .object({
44
+ id: z.string(),
45
+ threadId: z.string(),
46
+ objective: z.string(),
47
+ state: z.enum(goalStates),
48
+ revision: z.number().int().positive(),
49
+ createdAt: z.string(),
50
+ updatedAt: z.string(),
51
+ finishedAt: z.string().nullable(),
52
+ completionSummary: z.string().nullable(),
53
+ verificationEvidence: z.string().nullable(),
54
+ blockageExternalAction: z.string().nullable(),
55
+ blockageEvidence: z.string().nullable(),
56
+ blockageRepeatedTurns: z.number().int().nullable(),
57
+ pauseReasonCode: z
58
+ .enum(["manual", "archived", "failure", "usage-limit", "no-progress"])
59
+ .nullable(),
60
+ pauseReason: z.string().nullable(),
61
+ usageLimitKind: z
62
+ .enum(["subscription-window", "credits", "spend-control", "unknown"])
63
+ .nullable(),
64
+ usageResetAt: z.string().nullable(),
65
+ noProgressConsecutiveCount: z.number().int().min(0),
66
+ noProgressLastContinuationId: z.string().nullable(),
67
+ noProgressAssistantResultFingerprint: z.string().nullable(),
68
+ noProgressEvidence: z
69
+ .object({
70
+ continuationId: z.string(),
71
+ requestEventId: z.string(),
72
+ requestSeq: z.number().int(),
73
+ requestId: z.string(),
74
+ acceptedEventId: z.string(),
75
+ acceptedSeq: z.number().int(),
76
+ turnId: z.string(),
77
+ terminalEventId: z.string(),
78
+ terminalSeq: z.number().int(),
79
+ signals: z.array(
80
+ z.enum([
81
+ "tool-call",
82
+ "file-mutation",
83
+ "external-action",
84
+ "pending-interaction",
85
+ "changed-assistant-result",
86
+ ]),
87
+ ),
88
+ assistantResultFingerprint: z.string().nullable(),
89
+ previousAssistantResultFingerprint: z.string().nullable(),
90
+ assessment: z.enum(["progress", "no-progress"]),
91
+ observedAt: z.string(),
92
+ })
93
+ .strict()
94
+ .nullable(),
95
+ })
96
+ .strict();
97
+
98
+ export const goalCompleteInputSchema = z
99
+ .object({
100
+ goalId: z.string().min(1),
101
+ expectedRevision: z.number().int().positive(),
102
+ summary: z.string().trim().min(1),
103
+ verificationEvidence: z.string().trim().min(1),
104
+ })
105
+ .strict();
106
+
107
+ export const goalBlockedInputSchema = z
108
+ .object({
109
+ goalId: z.string().min(1),
110
+ expectedRevision: z.number().int().positive(),
111
+ externalAction: z.string().trim().min(1),
112
+ evidence: z.string().trim().min(1),
113
+ repeatedTurns: z.number().int().min(1),
114
+ })
115
+ .strict();
116
+
117
+ const goalGuardSchema = {
118
+ threadId: z.string().min(1),
119
+ goalId: z.string().min(1),
120
+ expectedRevision: z.number().int().positive(),
121
+ };
122
+
123
+ export const rpcContract = defineRpcContract({
124
+ start: {
125
+ input: z
126
+ .object({ threadId: z.string().min(1), objective: z.string().min(1) })
127
+ .strict(),
128
+ output: z.object({ goal: goalSchema }).strict(),
129
+ },
130
+ status: {
131
+ input: z.object({ threadId: z.string().min(1) }).strict(),
132
+ output: z.object({ goal: goalSchema.nullable() }).strict(),
133
+ },
134
+ edit: {
135
+ input: z
136
+ .object({ ...goalGuardSchema, objective: z.string().min(1) })
137
+ .strict(),
138
+ output: z.object({ goal: goalSchema }).strict(),
139
+ },
140
+ pause: {
141
+ input: z.object(goalGuardSchema).strict(),
142
+ output: z.object({ goal: goalSchema }).strict(),
143
+ },
144
+ resume: {
145
+ input: z.object(goalGuardSchema).strict(),
146
+ output: z.object({ goal: goalSchema }).strict(),
147
+ },
148
+ cancel: {
149
+ input: z.object(goalGuardSchema).strict(),
150
+ output: z.object({ goal: goalSchema }).strict(),
151
+ },
152
+ history: {
153
+ input: z
154
+ .object({
155
+ threadId: z.string().min(1),
156
+ limit: z.number().int().min(1).max(GOAL_HISTORY_MAX_LIMIT),
157
+ cursor: z.string().min(1).nullable(),
158
+ })
159
+ .strict(),
160
+ output: z
161
+ .object({
162
+ goals: z.array(goalSchema),
163
+ nextCursor: z.string().nullable(),
164
+ })
165
+ .strict(),
166
+ },
167
+ show: {
168
+ input: z.object({ goalId: z.string().min(1) }).strict(),
169
+ output: z.object({ goal: goalSchema }).strict(),
170
+ },
171
+ delete: {
172
+ input: z.object(goalGuardSchema).strict(),
173
+ output: z.object({ goal: goalSchema }).strict(),
174
+ },
175
+ });
176
+
177
+ interface PluginDependencies {
178
+ readonly makeRuntime: (
179
+ database: BetterSqlite3.Database,
180
+ gateway: GoalThreadGatewayAdapter,
181
+ ) => GoalRuntime;
182
+ }
183
+
184
+ const liveDependencies: PluginDependencies = { makeRuntime: makeGoalRuntime };
185
+
186
+ class CliUsageError extends Error {}
187
+
188
+ function requireGoalSuccessful(result: GoalCommandResult): GoalDto | null {
189
+ if (!result.ok) {
190
+ throw new Error(`[${result.error.code}] ${result.error.message}`);
191
+ }
192
+ if (!("goal" in result)) {
193
+ throw new Error("Goal command returned history instead of a Goal.");
194
+ }
195
+ return result.goal;
196
+ }
197
+
198
+ function requireHistorySuccessful(result: GoalCommandResult): GoalHistoryPage {
199
+ if (!result.ok) {
200
+ throw new Error(`[${result.error.code}] ${result.error.message}`);
201
+ }
202
+ if (!("page" in result)) {
203
+ throw new Error("Goal history command returned a Goal instead of history.");
204
+ }
205
+ return result.page;
206
+ }
207
+
208
+ function formatGoal(goal: GoalDto, heading: string): string {
209
+ return [
210
+ heading,
211
+ `ID: ${goal.id}`,
212
+ `Thread: ${goal.threadId}`,
213
+ `State: ${goal.state}`,
214
+ `Revision: ${goal.revision}`,
215
+ `Objective: ${goal.objective}`,
216
+ ...(goal.completionSummary === null
217
+ ? []
218
+ : [`Completion summary: ${goal.completionSummary}`]),
219
+ ...(goal.verificationEvidence === null
220
+ ? []
221
+ : [`Verification evidence: ${goal.verificationEvidence}`]),
222
+ ...(goal.blockageExternalAction === null
223
+ ? []
224
+ : [`External action required: ${goal.blockageExternalAction}`]),
225
+ ...(goal.blockageEvidence === null
226
+ ? []
227
+ : [`Blockage evidence: ${goal.blockageEvidence}`]),
228
+ ...(goal.blockageRepeatedTurns === null
229
+ ? []
230
+ : [`Repeated blocker turns: ${goal.blockageRepeatedTurns}`]),
231
+ ...(goal.pauseReason === null
232
+ ? []
233
+ : [`Pause reason: ${goal.pauseReason}`]),
234
+ ...(goal.usageLimitKind === null
235
+ ? []
236
+ : [`Usage limit: ${goal.usageLimitKind}`]),
237
+ ...(goal.usageResetAt === null
238
+ ? goal.pauseReasonCode === "usage-limit"
239
+ ? ["Manual resume required: yes"]
240
+ : []
241
+ : [`Usage reset at: ${goal.usageResetAt}`]),
242
+ `Consecutive no-progress Continuations: ${goal.noProgressConsecutiveCount}`,
243
+ ...(goal.noProgressLastContinuationId === null
244
+ ? []
245
+ : [`Last assessed Continuation: ${goal.noProgressLastContinuationId}`]),
246
+ ...(goal.noProgressEvidence === null
247
+ ? []
248
+ : [
249
+ `No-progress evidence: ${goal.noProgressEvidence.assessment}; turn ${goal.noProgressEvidence.turnId}; terminal sequence ${goal.noProgressEvidence.terminalSeq}; signals ${goal.noProgressEvidence.signals.join(", ") || "none"}`,
250
+ ]),
251
+ ].join("\n");
252
+ }
253
+
254
+ function jsonLine(value: unknown): string {
255
+ return `${JSON.stringify(value)}\n`;
256
+ }
257
+
258
+ function resultExitCode(result: GoalCommandResult): number {
259
+ if (result.ok) return 0;
260
+ switch (result.error.code) {
261
+ case "invalid_arguments":
262
+ case "invalid_cursor":
263
+ case "invalid_objective":
264
+ case "invalid_completion":
265
+ case "invalid_blockage":
266
+ return 2;
267
+ case "thread_not_found":
268
+ case "goal_not_found":
269
+ return 3;
270
+ case "goal_already_exists":
271
+ case "stale_goal":
272
+ case "invalid_transition":
273
+ case "thread_archived":
274
+ return 4;
275
+ case "persistence_error":
276
+ case "gateway_error":
277
+ return 1;
278
+ }
279
+ }
280
+
281
+ function commandResult(
282
+ result: GoalCommandResult,
283
+ json: boolean,
284
+ successHeading: string,
285
+ emptyMessage: string,
286
+ ): PluginCliResult {
287
+ const exitCode = resultExitCode(result);
288
+ if (!result.ok) {
289
+ return {
290
+ exitCode,
291
+ stderr: json
292
+ ? jsonLine({ ok: false, error: result.error })
293
+ : `${result.error.message}\n`,
294
+ };
295
+ }
296
+ if (!("goal" in result)) {
297
+ return { exitCode: 1, stderr: "Goal command returned invalid output.\n" };
298
+ }
299
+ if (json) return { exitCode: 0, stdout: jsonLine({ goal: result.goal }) };
300
+ return {
301
+ exitCode: 0,
302
+ stdout:
303
+ result.goal === null
304
+ ? `${emptyMessage}\n`
305
+ : `${formatGoal(result.goal, successHeading)}\n`,
306
+ };
307
+ }
308
+
309
+ function historyResult(
310
+ result: GoalCommandResult,
311
+ json: boolean,
312
+ threadId: string,
313
+ ): PluginCliResult {
314
+ const exitCode = resultExitCode(result);
315
+ if (!result.ok) {
316
+ return {
317
+ exitCode,
318
+ stderr: json
319
+ ? jsonLine({ ok: false, error: result.error })
320
+ : `${result.error.message}\n`,
321
+ };
322
+ }
323
+ if (!("page" in result)) {
324
+ return { exitCode: 1, stderr: "Goal history returned invalid output.\n" };
325
+ }
326
+ if (json) return { exitCode: 0, stdout: jsonLine(result.page) };
327
+ if (result.page.goals.length === 0) {
328
+ return { exitCode: 0, stdout: `No Goal history for thread ${threadId}.\n` };
329
+ }
330
+ const output = result.page.goals
331
+ .map((goal, index) => formatGoal(goal, index === 0 ? "Goal History" : "---"))
332
+ .join("\n");
333
+ return {
334
+ exitCode: 0,
335
+ stdout: `${output}${
336
+ result.page.nextCursor === null
337
+ ? ""
338
+ : `\nNext cursor: ${result.page.nextCursor}`
339
+ }\n`,
340
+ };
341
+ }
342
+
343
+ interface ParsedOptions {
344
+ readonly json: boolean;
345
+ readonly objectiveFile: string | null;
346
+ readonly limit: number | null;
347
+ readonly cursor: string | null;
348
+ readonly yes: boolean;
349
+ readonly positional: string[];
350
+ }
351
+
352
+ interface AllowedOptions {
353
+ readonly objectiveFile?: boolean;
354
+ readonly pagination?: boolean;
355
+ readonly yes?: boolean;
356
+ }
357
+
358
+ function parseOptions(
359
+ argv: string[],
360
+ allowed: AllowedOptions = {},
361
+ ): ParsedOptions {
362
+ let json = false;
363
+ let objectiveFile: string | null = null;
364
+ let limit: number | null = null;
365
+ let cursor: string | null = null;
366
+ let yes = false;
367
+ const positional: string[] = [];
368
+
369
+ const takeValue = (index: number, option: string): string => {
370
+ const value = argv[index + 1];
371
+ if (value === undefined || value.startsWith("--")) {
372
+ throw new CliUsageError(`${option} requires a value.`);
373
+ }
374
+ return value;
375
+ };
376
+
377
+ for (let index = 0; index < argv.length; index += 1) {
378
+ const argument = argv[index]!;
379
+ if (argument === "--json") {
380
+ json = true;
381
+ continue;
382
+ }
383
+ if (argument === "--yes") {
384
+ if (!allowed.yes) {
385
+ throw new CliUsageError("--yes is valid only for goal delete.");
386
+ }
387
+ yes = true;
388
+ continue;
389
+ }
390
+ if (
391
+ argument === "--objective-file" ||
392
+ argument.startsWith("--objective-file=")
393
+ ) {
394
+ if (!allowed.objectiveFile) {
395
+ throw new CliUsageError("--objective-file is valid only for goal start.");
396
+ }
397
+ if (objectiveFile !== null) {
398
+ throw new CliUsageError("--objective-file may be provided only once.");
399
+ }
400
+ objectiveFile = argument.includes("=")
401
+ ? argument.slice("--objective-file=".length)
402
+ : takeValue(index, "--objective-file");
403
+ if (!argument.includes("=")) index += 1;
404
+ if (objectiveFile.length === 0) {
405
+ throw new CliUsageError("--objective-file requires a path.");
406
+ }
407
+ continue;
408
+ }
409
+ if (argument === "--limit" || argument.startsWith("--limit=")) {
410
+ if (!allowed.pagination) {
411
+ throw new CliUsageError("--limit is valid only for goal history.");
412
+ }
413
+ if (limit !== null) {
414
+ throw new CliUsageError("--limit may be provided only once.");
415
+ }
416
+ const raw = argument.includes("=")
417
+ ? argument.slice("--limit=".length)
418
+ : takeValue(index, "--limit");
419
+ if (!argument.includes("=")) index += 1;
420
+ limit = Number(raw);
421
+ if (
422
+ !Number.isInteger(limit) ||
423
+ limit < 1 ||
424
+ limit > GOAL_HISTORY_MAX_LIMIT
425
+ ) {
426
+ throw new CliUsageError(
427
+ `--limit must be an integer between 1 and ${GOAL_HISTORY_MAX_LIMIT}.`,
428
+ );
429
+ }
430
+ continue;
431
+ }
432
+ if (argument === "--cursor" || argument.startsWith("--cursor=")) {
433
+ if (!allowed.pagination) {
434
+ throw new CliUsageError("--cursor is valid only for goal history.");
435
+ }
436
+ if (cursor !== null) {
437
+ throw new CliUsageError("--cursor may be provided only once.");
438
+ }
439
+ cursor = argument.includes("=")
440
+ ? argument.slice("--cursor=".length)
441
+ : takeValue(index, "--cursor");
442
+ if (!argument.includes("=")) index += 1;
443
+ if (cursor.length === 0) {
444
+ throw new CliUsageError("--cursor requires a value.");
445
+ }
446
+ continue;
447
+ }
448
+ if (argument.startsWith("--")) {
449
+ throw new CliUsageError(`Unknown option ${argument}.`);
450
+ }
451
+ positional.push(argument);
452
+ }
453
+
454
+ return { json, objectiveFile, limit, cursor, yes, positional };
455
+ }
456
+
457
+ function resolveThreadId(
458
+ explicit: string | undefined,
459
+ ctx: PluginCliContext,
460
+ ): string {
461
+ const threadId = explicit ?? ctx.threadId;
462
+ if (threadId === undefined) {
463
+ throw new CliUsageError(
464
+ "No thread ID was provided and no current BB thread context is available.",
465
+ );
466
+ }
467
+ return threadId;
468
+ }
469
+
470
+ async function invokingHostId(
471
+ bb: BbPluginApi,
472
+ ctx: PluginCliContext,
473
+ ): Promise<string | undefined> {
474
+ if (ctx.threadId === undefined) return undefined;
475
+ const thread = await bb.sdk.threads.get({
476
+ threadId: ctx.threadId,
477
+ signal: ctx.signal,
478
+ });
479
+ if (thread.environmentId === null) return undefined;
480
+ const environment = await bb.sdk.environments.get({
481
+ environmentId: thread.environmentId,
482
+ signal: ctx.signal,
483
+ });
484
+ return environment.hostId;
485
+ }
486
+
487
+ async function readObjectiveFile(
488
+ bb: BbPluginApi,
489
+ path: string,
490
+ ctx: PluginCliContext,
491
+ ): Promise<string> {
492
+ const absolutePath = isAbsolute(path)
493
+ ? path
494
+ : ctx.cwd === undefined
495
+ ? (() => {
496
+ throw new CliUsageError(
497
+ "A relative objective file requires CLI working-directory context.",
498
+ );
499
+ })()
500
+ : resolve(ctx.cwd, path);
501
+ const hostId = await invokingHostId(bb, ctx);
502
+ const file = await bb.sdk.files.read({
503
+ ...(hostId === undefined ? {} : { hostId }),
504
+ path: absolutePath,
505
+ signal: ctx.signal,
506
+ });
507
+ return file.contentEncoding === "base64"
508
+ ? Buffer.from(file.content, "base64").toString("utf8")
509
+ : file.content;
510
+ }
511
+
512
+ function goalAgentInstructions(goal: GoalDto): string {
513
+ const rules = [
514
+ "An active BB Goal governs this thread.",
515
+ `Exact Goal ID: ${goal.id}`,
516
+ `Goal revision: ${goal.revision}`,
517
+ "Keep working until the full objective is complete. Do not stop after only a plan or partial progress.",
518
+ "Only the user may edit, pause, resume, cancel, or delete this Goal.",
519
+ "Call bb_goal_complete only after every requirement is satisfied and verified. Pass the exact Goal ID and revision shown here, a concrete completion summary, and verification evidence.",
520
+ "Call bb_goal_blocked only for a genuine external impasse that requires a user or external action. Do not use it for ordinary difficulty, uncertainty, provider failures, usage limits, pending interactions, or a blocker that changed. The same external blocker must persist for at least three consecutive Goal turns. Pass the exact Goal ID and revision, the required external action, concrete evidence, and the repeated-turn count.",
521
+ "A stale Goal ID or revision cannot complete or block an edited, terminal, or replacement Goal.",
522
+ "Objective:",
523
+ ].join("\n");
524
+ const maxLength = 4096;
525
+ const remaining = Math.max(0, maxLength - rules.length - 1);
526
+ const truncationMarker = "\n[Objective truncated by BB limit]";
527
+ const objective =
528
+ goal.objective.length <= remaining
529
+ ? goal.objective
530
+ : `${goal.objective.slice(
531
+ 0,
532
+ Math.max(0, remaining - truncationMarker.length),
533
+ )}${truncationMarker}`;
534
+ return `${rules}\n${objective}`;
535
+ }
536
+
537
+ function goalCompleteParameters(goal: GoalDto): Record<string, unknown> {
538
+ return {
539
+ type: "object",
540
+ additionalProperties: false,
541
+ required: [
542
+ "goalId",
543
+ "expectedRevision",
544
+ "summary",
545
+ "verificationEvidence",
546
+ ],
547
+ properties: {
548
+ goalId: { type: "string", const: goal.id },
549
+ expectedRevision: { type: "integer", const: goal.revision },
550
+ summary: { type: "string", minLength: 1 },
551
+ verificationEvidence: { type: "string", minLength: 1 },
552
+ },
553
+ };
554
+ }
555
+
556
+ function goalBlockedParameters(goal: GoalDto): Record<string, unknown> {
557
+ return {
558
+ type: "object",
559
+ additionalProperties: false,
560
+ required: [
561
+ "goalId",
562
+ "expectedRevision",
563
+ "externalAction",
564
+ "evidence",
565
+ "repeatedTurns",
566
+ ],
567
+ properties: {
568
+ goalId: { type: "string", const: goal.id },
569
+ expectedRevision: { type: "integer", const: goal.revision },
570
+ externalAction: { type: "string", minLength: 1 },
571
+ evidence: { type: "string", minLength: 1 },
572
+ repeatedTurns: { type: "integer", minimum: 1 },
573
+ },
574
+ };
575
+ }
576
+
577
+ function publishGoalChanged(
578
+ bb: BbPluginApi,
579
+ goal: GoalDto,
580
+ deleted = false,
581
+ ): void {
582
+ bb.realtime.publish(GOAL_REALTIME_CHANNEL, {
583
+ threadId: goal.threadId,
584
+ goalId: goal.id,
585
+ revision: goal.revision,
586
+ state: goal.state,
587
+ pauseReasonCode: goal.pauseReasonCode,
588
+ noProgressConsecutiveCount: goal.noProgressConsecutiveCount,
589
+ noProgressEvidence: goal.noProgressEvidence,
590
+ deleted,
591
+ });
592
+ }
593
+
594
+ function publishThreadInvalidation(
595
+ bb: BbPluginApi,
596
+ threadId: string,
597
+ lifecycle: "archived" | "deleted",
598
+ ): void {
599
+ bb.realtime.publish(GOAL_REALTIME_CHANNEL, {
600
+ threadId,
601
+ goalId: null,
602
+ revision: null,
603
+ state: null,
604
+ pauseReasonCode: lifecycle === "archived" ? "archived" : null,
605
+ noProgressConsecutiveCount: null,
606
+ noProgressEvidence: null,
607
+ deleted: lifecycle === "deleted",
608
+ lifecycle,
609
+ });
610
+ }
611
+
612
+ function isThreadMissingError(cause: unknown): boolean {
613
+ return cause instanceof Error && /(?:not found|\b404\b)/i.test(cause.message);
614
+ }
615
+
616
+ async function runStart(
617
+ bb: BbPluginApi,
618
+ runtime: GoalRuntime,
619
+ argv: string[],
620
+ ctx: PluginCliContext,
621
+ ): Promise<PluginCliResult> {
622
+ const options = parseOptions(argv, { objectiveFile: true });
623
+ const firstIsThread = options.positional[0]?.startsWith("thr_") ?? false;
624
+ const explicitThread = firstIsThread ? options.positional[0] : undefined;
625
+ const objectiveWords = options.positional.slice(firstIsThread ? 1 : 0);
626
+
627
+ if (options.objectiveFile !== null && objectiveWords.length > 0) {
628
+ throw new CliUsageError(
629
+ "Provide an objective as text or with --objective-file, not both.",
630
+ );
631
+ }
632
+ if (options.objectiveFile === null && objectiveWords.length === 0) {
633
+ throw new CliUsageError(
634
+ "Usage: bb goal start [thread-id] <objective> [--objective-file <path>] [--json]",
635
+ );
636
+ }
637
+
638
+ const threadId = resolveThreadId(explicitThread, ctx);
639
+ const objective =
640
+ options.objectiveFile === null
641
+ ? objectiveWords.join(" ")
642
+ : await readObjectiveFile(bb, options.objectiveFile, ctx);
643
+ const result = await runtime.run({ type: "start", threadId, objective });
644
+ if (result.ok && "goal" in result && result.goal !== null) {
645
+ publishGoalChanged(bb, result.goal);
646
+ }
647
+ return commandResult(
648
+ result,
649
+ options.json,
650
+ "Started Goal",
651
+ `No unfinished Goal for thread ${threadId}.`,
652
+ );
653
+ }
654
+
655
+ async function runStatus(
656
+ runtime: GoalRuntime,
657
+ argv: string[],
658
+ ctx: PluginCliContext,
659
+ ): Promise<PluginCliResult> {
660
+ const options = parseOptions(argv);
661
+ if (options.positional.length > 1) {
662
+ throw new CliUsageError("Usage: bb goal status [thread-id] [--json]");
663
+ }
664
+ const threadId = resolveThreadId(options.positional[0], ctx);
665
+ const result = await runtime.run({ type: "status", threadId });
666
+ return commandResult(
667
+ result,
668
+ options.json,
669
+ "Active Goal",
670
+ `No unfinished Goal for thread ${threadId}.`,
671
+ );
672
+ }
673
+
674
+ function missingCurrentGoal(threadId: string): GoalCommandResult {
675
+ return {
676
+ ok: false,
677
+ error: {
678
+ code: "goal_not_found",
679
+ message: `No unfinished Goal for thread ${threadId}.`,
680
+ },
681
+ };
682
+ }
683
+
684
+ async function runMutation(
685
+ bb: BbPluginApi,
686
+ runtime: GoalRuntime,
687
+ type: GoalMutationType,
688
+ argv: string[],
689
+ ctx: PluginCliContext,
690
+ ): Promise<PluginCliResult> {
691
+ const options = parseOptions(argv);
692
+ const firstIsThread = options.positional[0]?.startsWith("thr_") ?? false;
693
+ const explicitThread = firstIsThread ? options.positional[0] : undefined;
694
+ const remaining = options.positional.slice(firstIsThread ? 1 : 0);
695
+
696
+ if (type === "edit") {
697
+ if (remaining.length === 0) {
698
+ throw new CliUsageError(
699
+ "Usage: bb goal edit [thread-id] <objective> [--json]",
700
+ );
701
+ }
702
+ } else if (remaining.length > 0) {
703
+ throw new CliUsageError(`Usage: bb goal ${type} [thread-id] [--json]`);
704
+ }
705
+
706
+ const threadId = resolveThreadId(explicitThread, ctx);
707
+ const status = await runtime.run({ type: "status", threadId });
708
+ if (!status.ok) return commandResult(status, options.json, "", "");
709
+ if (!("goal" in status)) {
710
+ return { exitCode: 1, stderr: "Goal status returned invalid output.\n" };
711
+ }
712
+ if (status.goal === null) {
713
+ return commandResult(missingCurrentGoal(threadId), options.json, "", "");
714
+ }
715
+
716
+ const guard = {
717
+ threadId,
718
+ goalId: status.goal.id,
719
+ expectedRevision: status.goal.revision,
720
+ };
721
+ const result =
722
+ type === "edit"
723
+ ? await runtime.run({
724
+ type,
725
+ ...guard,
726
+ objective: remaining.join(" "),
727
+ })
728
+ : await runtime.run({ type, ...guard });
729
+ if (result.ok && "goal" in result && result.goal !== null) {
730
+ publishGoalChanged(bb, result.goal);
731
+ }
732
+
733
+ const headings: Record<GoalMutationType, string> = {
734
+ edit: "Edited Goal",
735
+ pause: "Paused Goal",
736
+ resume: "Resumed Goal",
737
+ cancel: "Canceled Goal",
738
+ };
739
+ return commandResult(result, options.json, headings[type], "");
740
+ }
741
+
742
+ async function runHistory(
743
+ runtime: GoalRuntime,
744
+ argv: string[],
745
+ ctx: PluginCliContext,
746
+ ): Promise<PluginCliResult> {
747
+ const options = parseOptions(argv, { pagination: true });
748
+ if (options.positional.length > 1) {
749
+ throw new CliUsageError(
750
+ "Usage: bb goal history [thread-id] [--limit <n>] [--cursor <cursor>] [--json]",
751
+ );
752
+ }
753
+ const threadId = resolveThreadId(options.positional[0], ctx);
754
+ const result = await runtime.run({
755
+ type: "history",
756
+ threadId,
757
+ limit: options.limit ?? GOAL_HISTORY_DEFAULT_LIMIT,
758
+ cursor: options.cursor,
759
+ });
760
+ return historyResult(result, options.json, threadId);
761
+ }
762
+
763
+ async function runShow(
764
+ runtime: GoalRuntime,
765
+ argv: string[],
766
+ ): Promise<PluginCliResult> {
767
+ const options = parseOptions(argv);
768
+ if (options.positional.length !== 1) {
769
+ throw new CliUsageError("Usage: bb goal show <goal-id> [--json]");
770
+ }
771
+ const result = await runtime.run({
772
+ type: "show",
773
+ goalId: options.positional[0]!,
774
+ });
775
+ return commandResult(result, options.json, "Goal", "");
776
+ }
777
+
778
+ async function runDelete(
779
+ bb: BbPluginApi,
780
+ runtime: GoalRuntime,
781
+ argv: string[],
782
+ ): Promise<PluginCliResult> {
783
+ const options = parseOptions(argv, { yes: true });
784
+ if (options.positional.length !== 1) {
785
+ throw new CliUsageError(
786
+ "Usage: bb goal delete <goal-id> --yes [--json]",
787
+ );
788
+ }
789
+ if (!options.yes) {
790
+ throw new CliUsageError("Deleting a Goal requires --yes.");
791
+ }
792
+
793
+ const shown = await runtime.run({
794
+ type: "show",
795
+ goalId: options.positional[0]!,
796
+ });
797
+ if (!shown.ok) return commandResult(shown, options.json, "", "");
798
+ if (!("goal" in shown) || shown.goal === null) {
799
+ return { exitCode: 1, stderr: "Goal show returned invalid output.\n" };
800
+ }
801
+ const result = await runtime.run({
802
+ type: "delete",
803
+ threadId: shown.goal.threadId,
804
+ goalId: shown.goal.id,
805
+ expectedRevision: shown.goal.revision,
806
+ });
807
+ if (result.ok && "goal" in result && result.goal !== null) {
808
+ publishGoalChanged(bb, result.goal, true);
809
+ }
810
+ return commandResult(result, options.json, "Deleted Goal", "");
811
+ }
812
+
813
+ async function runCli(
814
+ bb: BbPluginApi,
815
+ runtime: GoalRuntime,
816
+ argv: string[],
817
+ ctx: PluginCliContext,
818
+ ): Promise<PluginCliResult> {
819
+ const json = argv.includes("--json");
820
+ try {
821
+ const [command, ...rest] = argv;
822
+ if (command === "start") return await runStart(bb, runtime, rest, ctx);
823
+ if (command === "status") return await runStatus(runtime, rest, ctx);
824
+ if (command === "history") return await runHistory(runtime, rest, ctx);
825
+ if (command === "show") return await runShow(runtime, rest);
826
+ if (command === "delete") return await runDelete(bb, runtime, rest);
827
+ if (
828
+ command === "edit" ||
829
+ command === "pause" ||
830
+ command === "resume" ||
831
+ command === "cancel"
832
+ ) {
833
+ return await runMutation(bb, runtime, command, rest, ctx);
834
+ }
835
+ throw new CliUsageError(
836
+ "Usage: bb goal <start|status|edit|pause|resume|cancel|history|show|delete> ...",
837
+ );
838
+ } catch (cause) {
839
+ const message = cause instanceof Error ? cause.message : String(cause);
840
+ return {
841
+ exitCode: cause instanceof CliUsageError ? 2 : 1,
842
+ stderr: json
843
+ ? jsonLine({
844
+ ok: false,
845
+ error: {
846
+ code:
847
+ cause instanceof CliUsageError
848
+ ? "invalid_arguments"
849
+ : "adapter_error",
850
+ message,
851
+ },
852
+ })
853
+ : `${message}\n`,
854
+ };
855
+ }
856
+ }
857
+
858
+ type ThreadFailureClassification = ClassifiedGoalFailure & {
859
+ readonly observedEvents: ReadonlyArray<GoalFailureEventIdentity>;
860
+ };
861
+
862
+ type FailureEventScope =
863
+ | { readonly kind: "thread" }
864
+ | { readonly kind: "turn"; readonly turnId: string };
865
+
866
+ type FailureCorrelationEvent = {
867
+ readonly id: string;
868
+ readonly seq: number;
869
+ readonly createdAt: number;
870
+ readonly scope: FailureEventScope;
871
+ readonly type: string;
872
+ readonly data: unknown;
873
+ };
874
+
875
+ function objectData(data: unknown): Record<string, unknown> | null {
876
+ return typeof data === "object" && data !== null
877
+ ? (data as Record<string, unknown>)
878
+ : null;
879
+ }
880
+
881
+ const progressEventTypes = [
882
+ "client/turn/requested",
883
+ "turn/input/accepted",
884
+ "turn/completed",
885
+ "item/started",
886
+ "item/completed",
887
+ "turn/diff/updated",
888
+ "system/permissionGrant/lifecycle",
889
+ "system/userQuestion/lifecycle",
890
+ ] as const;
891
+
892
+ async function observeThreadContinuation(
893
+ bb: BbPluginApi,
894
+ threadId: string,
895
+ deliveryMarker: string,
896
+ signal?: AbortSignal,
897
+ ) {
898
+ const rows: GoalStructuredEventRow[] = [];
899
+ let beforeSeq: string | undefined;
900
+ while (true) {
901
+ const page = await bb.sdk.threads.events.list({
902
+ threadId,
903
+ ...(beforeSeq === undefined ? {} : { beforeSeq }),
904
+ order: "desc",
905
+ limit: "500",
906
+ types: progressEventTypes,
907
+ signal,
908
+ });
909
+ rows.push(
910
+ ...page.map((row) => ({
911
+ id: row.id,
912
+ seq: row.seq,
913
+ createdAt: row.createdAt,
914
+ scope: row.scope,
915
+ type: row.type,
916
+ data: row.data,
917
+ })),
918
+ );
919
+ const observation = observeSettledContinuation(rows, deliveryMarker);
920
+ if (observation !== null || page.length < 500) return observation;
921
+ const oldest = page.at(-1);
922
+ if (oldest === undefined) return null;
923
+ beforeSeq = String(oldest.seq);
924
+ }
925
+ }
926
+
927
+ async function classifyThreadFailure(
928
+ bb: BbPluginApi,
929
+ threadId: string,
930
+ fallbackMessage: string | null,
931
+ lifecycleCreatedAtMs: number,
932
+ signal?: AbortSignal,
933
+ ): Promise<ThreadFailureClassification> {
934
+ const runEventTypes = [
935
+ "client/turn/requested",
936
+ "provider/error",
937
+ "provider/rateLimits/updated",
938
+ "system/error",
939
+ "turn/completed",
940
+ "turn/input/accepted",
941
+ ] as const;
942
+ const requestPage = await bb.sdk.threads.events.list({
943
+ threadId,
944
+ order: "desc",
945
+ limit: "1",
946
+ types: ["client/turn/requested"],
947
+ signal,
948
+ });
949
+ const requestRow = requestPage.find(
950
+ (event) => event.type === "client/turn/requested",
951
+ );
952
+ const events = [...requestPage];
953
+ if (requestRow !== undefined) {
954
+ let afterSeq = String(requestRow.seq);
955
+ while (true) {
956
+ const page = await bb.sdk.threads.events.list({
957
+ threadId,
958
+ afterSeq,
959
+ order: "asc",
960
+ limit: "500",
961
+ types: runEventTypes,
962
+ signal,
963
+ });
964
+ events.push(...page);
965
+ if (page.length < 500) break;
966
+ const newest = page.at(-1);
967
+ if (newest === undefined) break;
968
+ afterSeq = String(newest.seq);
969
+ }
970
+ } else {
971
+ events.push(
972
+ ...(await bb.sdk.threads.events.list({
973
+ threadId,
974
+ order: "desc",
975
+ limit: "500",
976
+ types: [
977
+ "provider/error",
978
+ "provider/rateLimits/updated",
979
+ "system/error",
980
+ "turn/completed",
981
+ "turn/input/accepted",
982
+ ],
983
+ signal,
984
+ })),
985
+ );
986
+ }
987
+ const rows: FailureCorrelationEvent[] = [
988
+ ...new Map(events.map((event) => [event.id, event])).values(),
989
+ ].map((event) => ({
990
+ id: event.id,
991
+ seq: event.seq,
992
+ createdAt: event.createdAt,
993
+ scope: event.scope,
994
+ type: event.type,
995
+ data: event.data,
996
+ }));
997
+ const requests = rows
998
+ .filter((row) => row.type === "client/turn/requested")
999
+ .filter((row) => typeof objectData(row.data)?.requestId === "string")
1000
+ .sort((left, right) => left.seq - right.seq);
1001
+ const latestRequest = requests.at(-1);
1002
+ const acceptedByRequestId = new Map<string, FailureCorrelationEvent>();
1003
+ const completedByTurnId = new Map<string, FailureCorrelationEvent>();
1004
+ for (const row of rows) {
1005
+ const data = objectData(row.data);
1006
+ if (
1007
+ row.type === "turn/input/accepted" &&
1008
+ row.scope.kind === "turn" &&
1009
+ typeof data?.clientRequestId === "string"
1010
+ ) {
1011
+ if (!acceptedByRequestId.has(data.clientRequestId)) {
1012
+ acceptedByRequestId.set(data.clientRequestId, row);
1013
+ }
1014
+ }
1015
+ if (
1016
+ row.type === "turn/completed" &&
1017
+ row.scope.kind === "turn" &&
1018
+ data?.status === "failed"
1019
+ ) {
1020
+ completedByTurnId.set(row.scope.turnId, row);
1021
+ }
1022
+ }
1023
+ let failedRun: {
1024
+ readonly requestSeq: number;
1025
+ readonly completedSeq: number;
1026
+ readonly turnId: string;
1027
+ } | null = null;
1028
+ if (latestRequest !== undefined) {
1029
+ const requestId = objectData(latestRequest.data)?.requestId;
1030
+ if (typeof requestId === "string") {
1031
+ const accepted = acceptedByRequestId.get(requestId);
1032
+ if (
1033
+ accepted !== undefined &&
1034
+ accepted.seq > latestRequest.seq &&
1035
+ accepted.scope.kind === "turn"
1036
+ ) {
1037
+ const turnId = accepted.scope.turnId;
1038
+ const completed = completedByTurnId.get(turnId);
1039
+ if (completed !== undefined && completed.seq > accepted.seq) {
1040
+ failedRun = {
1041
+ requestSeq: latestRequest.seq,
1042
+ completedSeq: completed.seq,
1043
+ turnId,
1044
+ };
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ const structuredEvents = rows
1050
+ .filter((event) =>
1051
+ ["provider/error", "provider/rateLimits/updated", "system/error"].includes(
1052
+ event.type,
1053
+ ),
1054
+ )
1055
+ .filter(
1056
+ (event) =>
1057
+ failedRun !== null &&
1058
+ event.seq >= failedRun.requestSeq &&
1059
+ event.seq <= failedRun.completedSeq,
1060
+ )
1061
+ .map((event) => ({
1062
+ id: event.id,
1063
+ seq: event.seq,
1064
+ createdAt: event.createdAt,
1065
+ turnId:
1066
+ failedRun?.turnId ??
1067
+ (event.scope.kind === "turn" ? event.scope.turnId : null),
1068
+ type: event.type,
1069
+ data: event.data,
1070
+ }));
1071
+ const lifecycleEvent: GoalFailureEventIdentity = {
1072
+ id: `thread.failed:${threadId}:${failedRun?.completedSeq ?? lifecycleCreatedAtMs}`,
1073
+ seq: null,
1074
+ createdAt: lifecycleCreatedAtMs,
1075
+ turnId: failedRun?.turnId ?? null,
1076
+ };
1077
+ const classified = classifyGoalFailureWithIdentity(
1078
+ structuredEvents,
1079
+ Date.now(),
1080
+ fallbackMessage,
1081
+ );
1082
+ return {
1083
+ ...classified,
1084
+ event: classified.event ?? lifecycleEvent,
1085
+ observedEvents: [...structuredEvents, lifecycleEvent].map(
1086
+ ({ id, seq, createdAt, turnId }) => ({ id, seq, createdAt, turnId }),
1087
+ ),
1088
+ };
1089
+ }
1090
+
1091
+ export function createPlugin(
1092
+ dependencies: PluginDependencies = liveDependencies,
1093
+ ): (bb: BbPluginApi) => Promise<void> {
1094
+ return async function goalPlugin(bb) {
1095
+ const database = bb.storage.database();
1096
+ bb.storage.migrate(database, [...GOAL_MIGRATIONS]);
1097
+
1098
+ const runtime = dependencies.makeRuntime(database, {
1099
+ async threadExists(threadId) {
1100
+ try {
1101
+ const thread = await bb.sdk.threads.get({ threadId });
1102
+ return thread.deletedAt === null;
1103
+ } catch {
1104
+ return false;
1105
+ }
1106
+ },
1107
+ async readThreadOwnership(threadId) {
1108
+ try {
1109
+ const thread = await bb.sdk.threads.get({ threadId });
1110
+ return {
1111
+ exists: thread.deletedAt === null,
1112
+ archived: thread.archivedAt !== null,
1113
+ deleted: thread.deletedAt !== null,
1114
+ };
1115
+ } catch {
1116
+ return { exists: false, archived: false, deleted: true };
1117
+ }
1118
+ },
1119
+ async readThread(threadId, signal) {
1120
+ const thread = await bb.sdk.threads.get({ threadId, signal });
1121
+ if (thread.archivedAt !== null || thread.deletedAt !== null) {
1122
+ return {
1123
+ status: thread.status,
1124
+ runtimeStatus: thread.runtime.displayStatus,
1125
+ queuedMessageCount: 0,
1126
+ activePromptMode: null,
1127
+ pendingInteractionCount: 0,
1128
+ archived: thread.archivedAt !== null,
1129
+ deleted: thread.deletedAt !== null,
1130
+ };
1131
+ }
1132
+ const [queuedMessages, interactions, timeline] = await Promise.all([
1133
+ bb.sdk.threads.queuedMessages.list({ threadId, signal }),
1134
+ bb.sdk.threads.interactions.list({ threadId, signal }),
1135
+ bb.sdk.threads.timeline({
1136
+ threadId,
1137
+ signal,
1138
+ segmentLimit: "1",
1139
+ summaryOnly: "false",
1140
+ }),
1141
+ ]);
1142
+ return {
1143
+ status: thread.status,
1144
+ runtimeStatus: thread.runtime.displayStatus,
1145
+ queuedMessageCount: queuedMessages.length,
1146
+ activePromptMode: timeline.activePromptMode?.mode ?? null,
1147
+ pendingInteractionCount: interactions.filter(
1148
+ (interaction) =>
1149
+ interaction.status !== "resolved" &&
1150
+ interaction.status !== "interrupted",
1151
+ ).length,
1152
+ archived: false,
1153
+ deleted: false,
1154
+ };
1155
+ },
1156
+ async sendContinuation(threadId, deliveryMarker, signal) {
1157
+ if (signal?.aborted === true) {
1158
+ throw new Error("Goal plugin is shutting down.");
1159
+ }
1160
+ const thread = await bb.sdk.threads.get({ threadId, signal });
1161
+ if (thread.archivedAt !== null || thread.deletedAt !== null) {
1162
+ throw new Error("The owning thread is archived or deleted.");
1163
+ }
1164
+ await bb.sdk.threads.send({
1165
+ threadId,
1166
+ mode: "auto",
1167
+ input: [
1168
+ {
1169
+ type: "text",
1170
+ text: continuationPrompt(deliveryMarker),
1171
+ mentions: [],
1172
+ visibility: "agent-only",
1173
+ },
1174
+ ],
1175
+ });
1176
+ },
1177
+ async reconcileContinuation(threadId, deliveryMarker, signal) {
1178
+ const timeline = await bb.sdk.threads.timeline({
1179
+ threadId,
1180
+ signal,
1181
+ segmentLimit: "100",
1182
+ summaryOnly: "false",
1183
+ });
1184
+ return timeline.rows.some(
1185
+ (row) => "text" in row && row.text.includes(deliveryMarker),
1186
+ );
1187
+ },
1188
+ observeContinuation(threadId, deliveryMarker, signal) {
1189
+ return observeThreadContinuation(
1190
+ bb,
1191
+ threadId,
1192
+ deliveryMarker,
1193
+ signal,
1194
+ );
1195
+ },
1196
+ });
1197
+
1198
+ const CONTINUATION_RETRY_BASE_MS = 25;
1199
+ const CONTINUATION_RETRY_MAX_MS = 1_000;
1200
+ const OWNERSHIP_RETRY_BASE_MS = 25;
1201
+ const OWNERSHIP_RETRY_MAX_MS = 1_000;
1202
+ let disposed = false;
1203
+ const lifecycleAbortController = new AbortController();
1204
+ let wakeWorker: (() => void) | null = null;
1205
+ let wakePending = false;
1206
+ const pendingIdleEvents = new Map<
1207
+ string,
1208
+ { readonly threadId: string; readonly opportunityKey: string }
1209
+ >();
1210
+ const pendingOwnershipReconciliations = new Map<
1211
+ string,
1212
+ {
1213
+ readonly threadId: string;
1214
+ readonly attempt: number;
1215
+ readonly nextAttemptAt: number;
1216
+ }
1217
+ >();
1218
+ const ownershipReconciliationsInFlight = new Set<string>();
1219
+ const pendingIdleEventKey = (threadId: string, opportunityKey: string) =>
1220
+ `${threadId}\u0000${opportunityKey}`;
1221
+ const clearPendingIdleEvents = (threadId: string) => {
1222
+ for (const [key, event] of pendingIdleEvents) {
1223
+ if (event.threadId === threadId) pendingIdleEvents.delete(key);
1224
+ }
1225
+ };
1226
+ const wake = () => {
1227
+ const resolve = wakeWorker;
1228
+ if (resolve === null) {
1229
+ wakePending = true;
1230
+ return;
1231
+ }
1232
+ wakeWorker = null;
1233
+ resolve();
1234
+ };
1235
+ const waitForWork = (
1236
+ signal: AbortSignal,
1237
+ timeoutMs: number | null = null,
1238
+ ): Promise<void> => {
1239
+ if (signal.aborted) return Promise.resolve();
1240
+ if (wakePending) {
1241
+ wakePending = false;
1242
+ return Promise.resolve();
1243
+ }
1244
+ return new Promise((resolve) => {
1245
+ let timer: ReturnType<typeof setTimeout> | undefined;
1246
+ const finish = () => {
1247
+ if (timer !== undefined) clearTimeout(timer);
1248
+ signal.removeEventListener("abort", finish);
1249
+ if (wakeWorker === finish) wakeWorker = null;
1250
+ resolve();
1251
+ };
1252
+ wakeWorker = finish;
1253
+ signal.addEventListener("abort", finish, { once: true });
1254
+ if (timeoutMs !== null) timer = setTimeout(finish, timeoutMs);
1255
+ });
1256
+ };
1257
+
1258
+ const retryPendingIdleEvents = async (signal: AbortSignal) => {
1259
+ for (const [pendingKey, event] of pendingIdleEvents) {
1260
+ if (signal.aborted) return;
1261
+ const assessed = await runtime.assessSettledContinuations(signal);
1262
+ for (const goal of assessed) publishGoalChanged(bb, goal);
1263
+ await runtime.enqueueIdle(event.threadId, event.opportunityKey);
1264
+ pendingIdleEvents.delete(pendingKey);
1265
+ }
1266
+ };
1267
+
1268
+ const queueOwnershipReconciliation = (threadId: string) => {
1269
+ const existing = pendingOwnershipReconciliations.get(threadId);
1270
+ const now = Date.now();
1271
+ pendingOwnershipReconciliations.set(threadId, {
1272
+ threadId,
1273
+ attempt: existing?.attempt ?? 0,
1274
+ nextAttemptAt: Math.min(existing?.nextAttemptAt ?? now, now),
1275
+ });
1276
+ wake();
1277
+ };
1278
+
1279
+ const reconcileOneThreadOwnership = async (
1280
+ threadId: string,
1281
+ signal: AbortSignal,
1282
+ ) => {
1283
+ let thread;
1284
+ try {
1285
+ thread = await bb.sdk.threads.get({ threadId, signal });
1286
+ } catch (cause) {
1287
+ if (!isThreadMissingError(cause)) throw cause;
1288
+ if (signal.aborted || disposed) return;
1289
+ clearPendingIdleEvents(threadId);
1290
+ await runtime.deleteThread(threadId);
1291
+ if (signal.aborted || disposed) return;
1292
+ publishThreadInvalidation(bb, threadId, "deleted");
1293
+ return;
1294
+ }
1295
+ if (signal.aborted || disposed) return;
1296
+ if (thread.deletedAt !== null) {
1297
+ clearPendingIdleEvents(threadId);
1298
+ await runtime.deleteThread(threadId);
1299
+ if (signal.aborted || disposed) return;
1300
+ publishThreadInvalidation(bb, threadId, "deleted");
1301
+ return;
1302
+ }
1303
+ if (thread.archivedAt !== null) {
1304
+ clearPendingIdleEvents(threadId);
1305
+ const goal = await runtime.archiveThread(threadId);
1306
+ if (signal.aborted || disposed) return;
1307
+ if (goal === null) {
1308
+ publishThreadInvalidation(bb, threadId, "archived");
1309
+ } else {
1310
+ publishGoalChanged(bb, goal);
1311
+ }
1312
+ }
1313
+ };
1314
+
1315
+ const retryOneOwnershipReconciliation = async (
1316
+ threadId: string,
1317
+ signal: AbortSignal,
1318
+ ) => {
1319
+ const pending = pendingOwnershipReconciliations.get(threadId);
1320
+ if (
1321
+ pending === undefined ||
1322
+ pending.nextAttemptAt > Date.now() ||
1323
+ ownershipReconciliationsInFlight.has(threadId) ||
1324
+ signal.aborted ||
1325
+ disposed
1326
+ ) {
1327
+ return;
1328
+ }
1329
+ ownershipReconciliationsInFlight.add(threadId);
1330
+ try {
1331
+ await reconcileOneThreadOwnership(threadId, signal);
1332
+ if (
1333
+ !signal.aborted &&
1334
+ !disposed &&
1335
+ pendingOwnershipReconciliations.get(threadId) === pending
1336
+ ) {
1337
+ pendingOwnershipReconciliations.delete(threadId);
1338
+ }
1339
+ } catch (cause) {
1340
+ if (signal.aborted || disposed) return;
1341
+ const attempt = pending.attempt + 1;
1342
+ const delayMs = Math.min(
1343
+ OWNERSHIP_RETRY_BASE_MS * 2 ** Math.min(attempt - 1, 20),
1344
+ OWNERSHIP_RETRY_MAX_MS,
1345
+ );
1346
+ pendingOwnershipReconciliations.set(threadId, {
1347
+ threadId,
1348
+ attempt,
1349
+ nextAttemptAt: Date.now() + delayMs,
1350
+ });
1351
+ bb.log.error(
1352
+ `Could not reconcile Goal ownership for thread ${threadId}; retry ${attempt} in ${delayMs}ms: ${cause instanceof Error ? cause.message : String(cause)}`,
1353
+ );
1354
+ } finally {
1355
+ ownershipReconciliationsInFlight.delete(threadId);
1356
+ if (pendingOwnershipReconciliations.has(threadId)) wake();
1357
+ }
1358
+ };
1359
+
1360
+ const retryPendingOwnershipReconciliations = async (
1361
+ signal: AbortSignal,
1362
+ ) => {
1363
+ for (const { threadId } of pendingOwnershipReconciliations.values()) {
1364
+ if (signal.aborted || disposed) return;
1365
+ await retryOneOwnershipReconciliation(threadId, signal);
1366
+ }
1367
+ };
1368
+
1369
+ const nextOwnershipRetryWaitMs = (): number | null => {
1370
+ let nextAttemptAt: number | null = null;
1371
+ for (const pending of pendingOwnershipReconciliations.values()) {
1372
+ if (ownershipReconciliationsInFlight.has(pending.threadId)) continue;
1373
+ nextAttemptAt =
1374
+ nextAttemptAt === null
1375
+ ? pending.nextAttemptAt
1376
+ : Math.min(nextAttemptAt, pending.nextAttemptAt);
1377
+ }
1378
+ return nextAttemptAt === null
1379
+ ? null
1380
+ : Math.max(0, nextAttemptAt - Date.now());
1381
+ };
1382
+
1383
+ bb.events.on("thread.idle", async ({ thread }) => {
1384
+ if (disposed) return;
1385
+ const opportunityKey = `idle:${thread.updatedAt}`;
1386
+ const pendingKey = pendingIdleEventKey(thread.id, opportunityKey);
1387
+ try {
1388
+ const assessed = await runtime.assessSettledContinuations();
1389
+ for (const goal of assessed) publishGoalChanged(bb, goal);
1390
+ await runtime.enqueueIdle(thread.id, opportunityKey);
1391
+ pendingIdleEvents.delete(pendingKey);
1392
+ wake();
1393
+ } catch (cause) {
1394
+ if (disposed) return;
1395
+ pendingIdleEvents.set(pendingKey, {
1396
+ threadId: thread.id,
1397
+ opportunityKey,
1398
+ });
1399
+ bb.log.error(
1400
+ `Could not enqueue idle Continuation: ${
1401
+ cause instanceof Error ? cause.message : String(cause)
1402
+ }`,
1403
+ );
1404
+ wake();
1405
+ }
1406
+ });
1407
+
1408
+ bb.events.on("thread.created", async () => {
1409
+ // Creation and fork events are observe-only. Goal state remains keyed by
1410
+ // the new thread ID, so source data is never copied or inferred.
1411
+ });
1412
+
1413
+ bb.events.on("thread.archived", async ({ thread: observedThread }) => {
1414
+ if (disposed) return;
1415
+ queueOwnershipReconciliation(observedThread.id);
1416
+ await retryOneOwnershipReconciliation(
1417
+ observedThread.id,
1418
+ lifecycleAbortController.signal,
1419
+ );
1420
+ });
1421
+
1422
+ bb.events.on("thread.deleted", async ({ thread }) => {
1423
+ if (disposed) return;
1424
+ queueOwnershipReconciliation(thread.id);
1425
+ await retryOneOwnershipReconciliation(
1426
+ thread.id,
1427
+ lifecycleAbortController.signal,
1428
+ );
1429
+ });
1430
+
1431
+ bb.events.on("thread.failed", async ({ thread, error }) => {
1432
+ if (disposed) return;
1433
+ try {
1434
+ const classified = await classifyThreadFailure(
1435
+ bb,
1436
+ thread.id,
1437
+ error,
1438
+ thread.updatedAt,
1439
+ );
1440
+ const goal = await runtime.recordFailure(
1441
+ thread.id,
1442
+ classified.failure,
1443
+ classified.event ?? undefined,
1444
+ classified.observedEvents,
1445
+ );
1446
+ if (goal !== null) publishGoalChanged(bb, goal);
1447
+ wake();
1448
+ } catch (cause) {
1449
+ if (!disposed) {
1450
+ bb.log.error(
1451
+ `Could not record failed Goal turn: ${
1452
+ cause instanceof Error ? cause.message : String(cause)
1453
+ }`,
1454
+ );
1455
+ }
1456
+ }
1457
+ });
1458
+
1459
+ bb.background.service("continuations", {
1460
+ async start(signal) {
1461
+ let retryDelayMs = CONTINUATION_RETRY_BASE_MS;
1462
+ let ownershipReconciled = false;
1463
+ while (!signal.aborted && !disposed) {
1464
+ try {
1465
+ if (!ownershipReconciled) {
1466
+ for (const threadId of await runtime.ownedThreadIds()) {
1467
+ queueOwnershipReconciliation(threadId);
1468
+ }
1469
+ ownershipReconciled = true;
1470
+ }
1471
+ await retryPendingOwnershipReconciliations(signal);
1472
+ await retryPendingIdleEvents(signal);
1473
+ const recoveredGoals = await runtime.recoverUsageLimits();
1474
+ for (const goal of recoveredGoals) {
1475
+ await runtime.enqueueIdle(
1476
+ goal.threadId,
1477
+ `usage-reset:${goal.id}:${goal.revision}`,
1478
+ );
1479
+ }
1480
+ await runtime.recoverContinuations();
1481
+ const assessed = await runtime.assessSettledContinuations(signal);
1482
+ for (const goal of assessed) publishGoalChanged(bb, goal);
1483
+ let claimed = false;
1484
+ do {
1485
+ claimed = await runtime.processContinuation(signal, (goal) =>
1486
+ publishGoalChanged(bb, goal),
1487
+ );
1488
+ } while (claimed && !signal.aborted);
1489
+ retryDelayMs = CONTINUATION_RETRY_BASE_MS;
1490
+ if (!signal.aborted && !disposed) {
1491
+ const usageWaitMs = usageResetWaitMs(
1492
+ await runtime.nextUsageLimitReset(),
1493
+ Date.now(),
1494
+ );
1495
+ const ownershipWaitMs = nextOwnershipRetryWaitMs();
1496
+ const waitMs =
1497
+ usageWaitMs === null
1498
+ ? ownershipWaitMs
1499
+ : ownershipWaitMs === null
1500
+ ? usageWaitMs
1501
+ : Math.min(usageWaitMs, ownershipWaitMs);
1502
+ if (pendingIdleEvents.size > 0) continue;
1503
+ if (ownershipWaitMs === 0) continue;
1504
+ await waitForWork(signal, waitMs);
1505
+ }
1506
+ } catch (cause) {
1507
+ if (signal.aborted) break;
1508
+ bb.log.error(
1509
+ `Continuation worker recovered from an error: ${
1510
+ cause instanceof Error ? cause.message : String(cause)
1511
+ }`,
1512
+ );
1513
+ await waitForWork(signal, retryDelayMs);
1514
+ retryDelayMs = Math.min(
1515
+ retryDelayMs * 2,
1516
+ CONTINUATION_RETRY_MAX_MS,
1517
+ );
1518
+ }
1519
+ }
1520
+ },
1521
+ });
1522
+ const snapshots = makeCurrentGoalSnapshotReader(database);
1523
+
1524
+ bb.agents.registerTool({
1525
+ name: "bb_goal_complete",
1526
+ description:
1527
+ "Mark the active BB Goal completed after all required work is done and verified.",
1528
+ instructions:
1529
+ "Use only for the active BB Goal. Include its exact ID and revision, a completion summary, and concrete verification evidence.",
1530
+ presentation: {
1531
+ label: {
1532
+ pending: "Completing Goal",
1533
+ completed: "Completed Goal",
1534
+ },
1535
+ },
1536
+ parameters: goalCompleteInputSchema,
1537
+ async execute(input, context) {
1538
+ const goal = requireGoalSuccessful(
1539
+ await runtime.run({
1540
+ type: "complete",
1541
+ threadId: context.threadId,
1542
+ ...input,
1543
+ }),
1544
+ );
1545
+ if (goal === null) throw new Error("Goal Completion returned no Goal.");
1546
+ publishGoalChanged(bb, goal);
1547
+ return {
1548
+ content: [
1549
+ {
1550
+ type: "text",
1551
+ text: JSON.stringify({ goal }),
1552
+ },
1553
+ ],
1554
+ };
1555
+ },
1556
+ });
1557
+
1558
+ bb.agents.registerTool({
1559
+ name: "bb_goal_blocked",
1560
+ description:
1561
+ "Report a genuine external Blockage after the same blocker persists for at least three consecutive Goal turns.",
1562
+ instructions:
1563
+ "Use only for a genuine external impasse. Include the exact Goal ID and revision, the required external action, concrete evidence, and the repeated-turn count. Do not use for ordinary difficulty, uncertainty, failures, usage limits, pending interactions, or changed blockers.",
1564
+ presentation: {
1565
+ label: {
1566
+ pending: "Reporting Goal Blockage",
1567
+ completed: "Reported Goal Blockage",
1568
+ },
1569
+ },
1570
+ parameters: goalBlockedInputSchema,
1571
+ async execute(input, context) {
1572
+ const goal = requireGoalSuccessful(
1573
+ await runtime.run({
1574
+ type: "block",
1575
+ threadId: context.threadId,
1576
+ ...input,
1577
+ }),
1578
+ );
1579
+ if (goal === null) throw new Error("Goal Blockage returned no Goal.");
1580
+ publishGoalChanged(bb, goal);
1581
+ return {
1582
+ content: [
1583
+ {
1584
+ type: "text",
1585
+ text: JSON.stringify({
1586
+ goal,
1587
+ blockageReport:
1588
+ goal.state === "blocked"
1589
+ ? { status: "blocked", repeatedTurns: input.repeatedTurns }
1590
+ : {
1591
+ status: "qualifying",
1592
+ repeatedTurns: input.repeatedTurns,
1593
+ turnsRemaining: 3 - input.repeatedTurns,
1594
+ },
1595
+ }),
1596
+ },
1597
+ ],
1598
+ };
1599
+ },
1600
+ });
1601
+
1602
+ bb.agents.configure((context) => {
1603
+ const goal = snapshots.current(context.thread.id);
1604
+ if (goal === null || goal.state !== "active") {
1605
+ return { tools: [], skills: [] };
1606
+ }
1607
+ return {
1608
+ tools: [
1609
+ {
1610
+ name: "bb_goal_complete",
1611
+ parameters: goalCompleteParameters(goal),
1612
+ },
1613
+ {
1614
+ name: "bb_goal_blocked",
1615
+ parameters: goalBlockedParameters(goal),
1616
+ },
1617
+ ],
1618
+ skills: [],
1619
+ instructions: goalAgentInstructions(goal),
1620
+ };
1621
+ });
1622
+
1623
+ async function mutate(
1624
+ command:
1625
+ | {
1626
+ readonly type: "edit";
1627
+ readonly threadId: string;
1628
+ readonly goalId: string;
1629
+ readonly expectedRevision: number;
1630
+ readonly objective: string;
1631
+ }
1632
+ | {
1633
+ readonly type: "pause" | "resume" | "cancel";
1634
+ readonly threadId: string;
1635
+ readonly goalId: string;
1636
+ readonly expectedRevision: number;
1637
+ },
1638
+ ): Promise<{ goal: GoalDto }> {
1639
+ const goal = requireGoalSuccessful(await runtime.run(command));
1640
+ if (goal === null) {
1641
+ throw new Error(`Goal ${command.type} returned no Goal.`);
1642
+ }
1643
+ publishGoalChanged(bb, goal);
1644
+ return { goal };
1645
+ }
1646
+
1647
+ bb.rpc.register(rpcContract, {
1648
+ async start(input) {
1649
+ const goal = requireGoalSuccessful(
1650
+ await runtime.run({
1651
+ type: "start",
1652
+ threadId: input.threadId,
1653
+ objective: input.objective,
1654
+ }),
1655
+ );
1656
+ if (goal === null) throw new Error("Goal start returned no Goal.");
1657
+ publishGoalChanged(bb, goal);
1658
+ return { goal };
1659
+ },
1660
+ async status(input) {
1661
+ const goal = requireGoalSuccessful(
1662
+ await runtime.run({ type: "status", threadId: input.threadId }),
1663
+ );
1664
+ return { goal };
1665
+ },
1666
+ edit: (input) => mutate({ type: "edit", ...input }),
1667
+ pause: (input) => mutate({ type: "pause", ...input }),
1668
+ resume: (input) => mutate({ type: "resume", ...input }),
1669
+ cancel: (input) => mutate({ type: "cancel", ...input }),
1670
+ async history(input) {
1671
+ const page = requireHistorySuccessful(
1672
+ await runtime.run({ type: "history", ...input }),
1673
+ );
1674
+ return { goals: [...page.goals], nextCursor: page.nextCursor };
1675
+ },
1676
+ async show(input) {
1677
+ const goal = requireGoalSuccessful(
1678
+ await runtime.run({ type: "show", goalId: input.goalId }),
1679
+ );
1680
+ if (goal === null) throw new Error("Goal show returned no Goal.");
1681
+ return { goal };
1682
+ },
1683
+ async delete(input) {
1684
+ const goal = requireGoalSuccessful(
1685
+ await runtime.run({ type: "delete", ...input }),
1686
+ );
1687
+ if (goal === null) throw new Error("Goal delete returned no Goal.");
1688
+ publishGoalChanged(bb, goal, true);
1689
+ return { goal };
1690
+ },
1691
+ });
1692
+
1693
+ bb.cli.register({
1694
+ name: "goal",
1695
+ summary: "Start, inspect, and control durable thread Goals",
1696
+ commands: [
1697
+ {
1698
+ name: "start",
1699
+ summary: "Start a Goal on an existing thread",
1700
+ usage:
1701
+ "bb goal start [thread-id] <objective> [--objective-file <path>] [--json]",
1702
+ },
1703
+ {
1704
+ name: "status",
1705
+ summary: "Inspect the unfinished Goal for a thread",
1706
+ usage: "bb goal status [thread-id] [--json]",
1707
+ },
1708
+ {
1709
+ name: "edit",
1710
+ summary: "Edit the unfinished Goal objective",
1711
+ usage: "bb goal edit [thread-id] <objective> [--json]",
1712
+ },
1713
+ {
1714
+ name: "pause",
1715
+ summary: "Pause an active Goal",
1716
+ usage: "bb goal pause [thread-id] [--json]",
1717
+ },
1718
+ {
1719
+ name: "resume",
1720
+ summary: "Resume a paused Goal",
1721
+ usage: "bb goal resume [thread-id] [--json]",
1722
+ },
1723
+ {
1724
+ name: "cancel",
1725
+ summary: "Cancel an unfinished Goal",
1726
+ usage: "bb goal cancel [thread-id] [--json]",
1727
+ },
1728
+ {
1729
+ name: "history",
1730
+ summary: "Browse a thread's Goal history",
1731
+ usage:
1732
+ "bb goal history [thread-id] [--limit <n>] [--cursor <cursor>] [--json]",
1733
+ },
1734
+ {
1735
+ name: "show",
1736
+ summary: "Inspect one Goal by ID",
1737
+ usage: "bb goal show <goal-id> [--json]",
1738
+ },
1739
+ {
1740
+ name: "delete",
1741
+ summary: "Delete one Goal after explicit confirmation",
1742
+ usage: "bb goal delete <goal-id> --yes [--json]",
1743
+ },
1744
+ ],
1745
+ run: (argv, ctx) => runCli(bb, runtime, argv, ctx),
1746
+ });
1747
+
1748
+ bb.onDispose(() => {
1749
+ disposed = true;
1750
+ lifecycleAbortController.abort();
1751
+ wake();
1752
+ return runtime.dispose();
1753
+ });
1754
+ bb.log.info("Goal coordinator loaded");
1755
+ };
1756
+ }
1757
+
1758
+ export default createPlugin();