@get-bb/plugin-sdk 0.6.157 → 0.6.164

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.
@@ -329,6 +329,23 @@ var PLUGIN_INTERACTION_MAX_TITLE_LENGTH = 160;
329
329
  var PLUGIN_INTERACTION_MAX_PAYLOAD_BYTES = 64 * 1024;
330
330
  var PLUGIN_INTERACTION_MAX_TIMEOUT_MS = 7 * 24 * 60 * 60 * 1e3;
331
331
 
332
+ // ../text-utils/src/utf16.ts
333
+ function isHighSurrogateAt(value, index) {
334
+ const code = value.charCodeAt(index);
335
+ return code >= 55296 && code <= 56319;
336
+ }
337
+ function isLowSurrogateAt(value, index) {
338
+ const code = value.charCodeAt(index);
339
+ return code >= 56320 && code <= 57343;
340
+ }
341
+ function sliceUtf16Head(value, maxChars) {
342
+ let end = Math.min(value.length, Math.max(0, maxChars));
343
+ if (isHighSurrogateAt(value, end - 1) && isLowSurrogateAt(value, end)) {
344
+ end -= 1;
345
+ }
346
+ return value.slice(0, end);
347
+ }
348
+
332
349
  // ../domain/src/plugin-icon.ts
333
350
  function isPluginOwnedIconPath(icon) {
334
351
  return icon.startsWith("./");
@@ -2268,7 +2285,9 @@ function runPluginStorageMigrations(database, statements) {
2268
2285
  if (!migrationColumns.some((column) => column.name === "statement_hash")) {
2269
2286
  database.exec("ALTER TABLE _bb_migrations ADD COLUMN statement_hash TEXT");
2270
2287
  }
2271
- const rows = database.prepare("SELECT id, statement_hash FROM _bb_migrations ORDER BY id").all();
2288
+ const rows = database.prepare(
2289
+ "SELECT id, statement_hash FROM _bb_migrations ORDER BY id"
2290
+ ).all();
2272
2291
  const applied = /* @__PURE__ */ new Map();
2273
2292
  for (const row of rows) applied.set(row.id, row.statement_hash);
2274
2293
  const statementHashes = statements.map(migrationStatementHash);
@@ -2821,7 +2840,10 @@ function normalizePluginAgentConfiguration(args) {
2821
2840
  if (output.instructions !== void 0 && typeof output.instructions !== "string") {
2822
2841
  throw new Error("configure() output.instructions must be a string");
2823
2842
  }
2824
- const instructions = typeof output.instructions === "string" && output.instructions.trim().length > 0 ? output.instructions.slice(0, PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS) : null;
2843
+ const instructions = typeof output.instructions === "string" && output.instructions.trim().length > 0 ? sliceUtf16Head(
2844
+ output.instructions,
2845
+ PLUGIN_DYNAMIC_INSTRUCTIONS_MAX_CHARS
2846
+ ) : null;
2825
2847
  const toolSelections = normalizePluginAgentToolSelections({
2826
2848
  knownIds: args.knownToolIds,
2827
2849
  pluginId: args.pluginId,
@@ -3041,6 +3063,10 @@ function createFakeSdk(options) {
3041
3063
  `bb.sdk.${path} is not stubbed \u2014 pass an implementation via createFakePluginHost({ sdk: { ... } }) or harness.sdk.stub("${path}", fn)`
3042
3064
  );
3043
3065
  }
3066
+ const track = options.trackThreadCreation;
3067
+ if (track !== void 0 && (path === "threads.spawn" || path === "threads.fork")) {
3068
+ return track(async () => stub(...args));
3069
+ }
3044
3070
  return stub(...args);
3045
3071
  }
3046
3072
  const nodes = /* @__PURE__ */ new Map();
@@ -3072,6 +3098,98 @@ function createFakeSdk(options) {
3072
3098
  return { sdk: node(""), harness };
3073
3099
  }
3074
3100
 
3101
+ // src/internal/thread-event-gate.ts
3102
+ function fromThread(thread) {
3103
+ return { threadId: thread.id, createdAt: thread.createdAt };
3104
+ }
3105
+ function fromThreadId(threadId) {
3106
+ return { threadId, createdAt: null };
3107
+ }
3108
+ var THREAD_OF_EVENT = {
3109
+ "experimental_environment.removed": () => null,
3110
+ "experimental_thread.events": ({ thread }) => fromThread(thread),
3111
+ "experimental_thread.parentChanged": ({ thread }) => fromThread(thread),
3112
+ "experimental_thread.read": ({ thread }) => fromThread(thread),
3113
+ "experimental_terminal.input": () => null,
3114
+ "experimental_host.deleted": () => null,
3115
+ "thread.created": ({ thread }) => fromThread(thread),
3116
+ "thread.active": ({ thread }) => fromThread(thread),
3117
+ "thread.idle": ({ thread }) => fromThread(thread),
3118
+ "thread.failed": ({ thread }) => fromThread(thread),
3119
+ "thread.archived": ({ thread }) => fromThread(thread),
3120
+ "thread.unarchived": ({ thread }) => fromThread(thread),
3121
+ "thread.deleted": ({ thread }) => fromThread(thread),
3122
+ "interaction.pending": ({ thread }) => fromThread(thread),
3123
+ "message.queued": ({ entry }) => fromThreadId(entry.threadId),
3124
+ "message.dispatched": ({ entry }) => fromThreadId(entry.threadId),
3125
+ "message.cancelled": ({ entry }) => fromThreadId(entry.threadId),
3126
+ "turn.failed": ({ threadId }) => fromThreadId(threadId),
3127
+ "experimental_thread.settled": ({ thread }) => fromThread(thread)
3128
+ };
3129
+ function threadOfEvent(event, payload) {
3130
+ const extract = THREAD_OF_EVENT[event];
3131
+ return extract(payload);
3132
+ }
3133
+ function createThreadEventGate(options = {}) {
3134
+ const now = options.now ?? Date.now;
3135
+ const schedule = options.schedule ?? ((run) => void setImmediate(run));
3136
+ const callsStartedAt = /* @__PURE__ */ new Map();
3137
+ let held = [];
3138
+ function createdDuringCall(createdAt) {
3139
+ if (createdAt === null) return false;
3140
+ for (const startedAt of callsStartedAt.values()) {
3141
+ if (startedAt <= createdAt) return true;
3142
+ }
3143
+ return false;
3144
+ }
3145
+ function release() {
3146
+ const pending = held;
3147
+ held = [];
3148
+ const stillHeld = /* @__PURE__ */ new Set();
3149
+ for (const entry of pending) {
3150
+ if (stillHeld.has(entry.threadId) || createdDuringCall(entry.createdAt)) {
3151
+ stillHeld.add(entry.threadId);
3152
+ held.push(entry);
3153
+ continue;
3154
+ }
3155
+ entry.deliver();
3156
+ }
3157
+ }
3158
+ return {
3159
+ async track(call) {
3160
+ const token = /* @__PURE__ */ Symbol("thread-creating-call");
3161
+ callsStartedAt.set(token, now());
3162
+ try {
3163
+ return await call();
3164
+ } finally {
3165
+ callsStartedAt.delete(token);
3166
+ schedule(release);
3167
+ }
3168
+ },
3169
+ deliver(subject, deliver) {
3170
+ if (subject === null) {
3171
+ deliver();
3172
+ return;
3173
+ }
3174
+ const threadId = subject.threadId;
3175
+ if (held.some((entry) => entry.threadId === threadId)) {
3176
+ held.push({ threadId, createdAt: null, deliver });
3177
+ return;
3178
+ }
3179
+ if (callsStartedAt.size === 0) {
3180
+ deliver();
3181
+ return;
3182
+ }
3183
+ const createdAt = subject.createdAt();
3184
+ if (!createdDuringCall(createdAt)) {
3185
+ deliver();
3186
+ return;
3187
+ }
3188
+ held.push({ threadId, createdAt, deliver });
3189
+ }
3190
+ };
3191
+ }
3192
+
3075
3193
  // src/testing/fake-plugin-host.ts
3076
3194
  var PluginContextStaleError = class extends Error {
3077
3195
  constructor(pluginId) {
@@ -3110,7 +3228,6 @@ function jsonRoundTrip(value, what) {
3110
3228
  function throwRpcError(error) {
3111
3229
  throw new experimental_PluginRpcCallError(error);
3112
3230
  }
3113
- var FAKE_TUNNEL_INGRESS_FIRST_PORT = 41e3;
3114
3231
  var fakeHostDisposers = /* @__PURE__ */ new WeakMap();
3115
3232
  function createFakePluginHost(options = {}) {
3116
3233
  return createFakePluginHostInternal(options);
@@ -3503,37 +3620,13 @@ function createFakePluginHostInternal(options, sharedState) {
3503
3620
  get experimental_dataDir() {
3504
3621
  assertLive();
3505
3622
  return dataDir;
3506
- },
3507
- async internal_DO_NOT_USE_openTunnelIngress(ingressOptions) {
3508
- assertLive();
3509
- const audience = ingressOptions?.audience;
3510
- if (typeof audience !== "string" || audience.length === 0) {
3511
- throw new Error(
3512
- "bb.server.internal_DO_NOT_USE_openTunnelIngress needs a non-empty audience"
3513
- );
3514
- }
3515
- const shared = tunnelIngresses.find(
3516
- (entry2) => entry2.audience === audience && !entry2.closed
3517
- );
3518
- const entry = {
3519
- audience,
3520
- baseUrl: shared?.baseUrl ?? `http://127.0.0.1:${FAKE_TUNNEL_INGRESS_FIRST_PORT + tunnelIngresses.length}`,
3521
- closed: false
3522
- };
3523
- tunnelIngresses.push(entry);
3524
- const close = async () => {
3525
- entry.closed = true;
3526
- const index = disposeHooks.indexOf(close);
3527
- if (index !== -1) disposeHooks.splice(index, 1);
3528
- };
3529
- disposeHooks.push(close);
3530
- return { baseUrl: entry.baseUrl, close };
3531
3623
  }
3532
3624
  };
3533
- const tunnelIngresses = [];
3625
+ const threadEventGate = createThreadEventGate();
3534
3626
  const { sdk, harness: sdkHarness } = createFakeSdk({
3535
3627
  pluginId,
3536
- overrides: options.sdk
3628
+ overrides: options.sdk,
3629
+ trackThreadCreation: (call) => threadEventGate.track(call)
3537
3630
  });
3538
3631
  const threadEventHandlers = {
3539
3632
  "experimental_thread.events": [],
@@ -3553,8 +3646,52 @@ function createFakePluginHostInternal(options, sharedState) {
3553
3646
  "message.dispatched": [],
3554
3647
  "turn.failed": [],
3555
3648
  "message.cancelled": [],
3649
+ "experimental_thread.settled": [],
3556
3650
  "thread.unarchived": []
3557
3651
  };
3652
+ function deliverThreadEvent(event, payload) {
3653
+ const thread = threadOfEvent(event, payload);
3654
+ return new Promise((resolve2) => {
3655
+ threadEventGate.deliver(
3656
+ thread === null ? null : { threadId: thread.threadId, createdAt: () => thread.createdAt },
3657
+ () => {
3658
+ void (async () => {
3659
+ const errors = [];
3660
+ for (const handler of [...threadEventHandlers[event]]) {
3661
+ try {
3662
+ await handler(payload);
3663
+ } catch (error) {
3664
+ errors.push(error);
3665
+ emitLog(
3666
+ "warn",
3667
+ `${event} handler failed: ${errorMessage(error)}`
3668
+ );
3669
+ }
3670
+ }
3671
+ resolve2({ errors });
3672
+ })();
3673
+ }
3674
+ );
3675
+ });
3676
+ }
3677
+ function settledEventFor(event, payload) {
3678
+ const delivered = {
3679
+ [event]: payload
3680
+ };
3681
+ if (delivered["thread.idle"] !== void 0) {
3682
+ return { outcome: "completed", ...delivered["thread.idle"] };
3683
+ }
3684
+ if (delivered["thread.failed"] !== void 0) {
3685
+ return { outcome: "failed", ...delivered["thread.failed"] };
3686
+ }
3687
+ if (delivered["thread.archived"] !== void 0) {
3688
+ return { outcome: "archived", ...delivered["thread.archived"] };
3689
+ }
3690
+ if (delivered["thread.deleted"] !== void 0) {
3691
+ return { outcome: "deleted", ...delivered["thread.deleted"] };
3692
+ }
3693
+ return null;
3694
+ }
3558
3695
  const hooks = {
3559
3696
  "message.dispatch": null
3560
3697
  };
@@ -3603,9 +3740,6 @@ function createFakePluginHostInternal(options, sharedState) {
3603
3740
  });
3604
3741
  }
3605
3742
  const sharedPortDeclarations = [];
3606
- let nextTunnelConfig = null;
3607
- let nextTunnelStatuses = [];
3608
- const nextTunnelListeners = /* @__PURE__ */ new Set();
3609
3743
  const hostRpcCalls = [];
3610
3744
  const hostWorkerExitSubscriptions = [];
3611
3745
  const hostSignalSubscriptions = [];
@@ -3737,27 +3871,10 @@ function createFakePluginHostInternal(options, sharedState) {
3737
3871
  } else {
3738
3872
  sharedPortDeclarations[existingIndex] = replacement;
3739
3873
  }
3740
- },
3741
- internal_DO_NOT_USE_setNextTunnels(config) {
3742
- assertLive();
3743
- nextTunnelConfig = config === null ? null : { domain: config.domain, server: { ...config.server } };
3744
- },
3745
- internal_DO_NOT_USE_nextTunnelStatuses() {
3746
- assertLive();
3747
- return structuredClone(nextTunnelStatuses);
3748
- },
3749
- internal_DO_NOT_USE_onNextTunnelStatusChange(listener) {
3750
- assertLive();
3751
- nextTunnelListeners.add(listener);
3752
- return () => {
3753
- nextTunnelListeners.delete(listener);
3754
- };
3755
3874
  }
3756
3875
  };
3757
3876
  disposeHooks.push(() => {
3758
3877
  sharedPortDeclarations.length = 0;
3759
- nextTunnelConfig = null;
3760
- nextTunnelListeners.clear();
3761
3878
  });
3762
3879
  const events = {
3763
3880
  on(event, handler) {
@@ -3983,15 +4100,7 @@ function createFakePluginHostInternal(options, sharedState) {
3983
4100
  get recheckCount() {
3984
4101
  return requestedDrains;
3985
4102
  },
3986
- internal_DO_NOT_USE_tunnelIngresses: tunnelIngresses,
3987
4103
  sharedPortDeclarations,
3988
- get internal_DO_NOT_USE_nextTunnelConfig() {
3989
- return nextTunnelConfig;
3990
- },
3991
- internal_DO_NOT_USE_setNextTunnelStatuses(statuses) {
3992
- nextTunnelStatuses = structuredClone([...statuses]);
3993
- for (const listener of [...nextTunnelListeners]) listener();
3994
- },
3995
4104
  experimental_hostRpcCalls: hostRpcCalls,
3996
4105
  sdk: sdkHarness,
3997
4106
  registrations: {
@@ -4037,6 +4146,7 @@ function createFakePluginHostInternal(options, sharedState) {
4037
4146
  "message.dispatched": threadEventHandlers["message.dispatched"].length,
4038
4147
  "turn.failed": threadEventHandlers["turn.failed"].length,
4039
4148
  "message.cancelled": threadEventHandlers["message.cancelled"].length,
4149
+ "experimental_thread.settled": threadEventHandlers["experimental_thread.settled"].length,
4040
4150
  "thread.unarchived": threadEventHandlers["thread.unarchived"].length
4041
4151
  };
4042
4152
  },
@@ -4429,14 +4539,12 @@ function createFakePluginHostInternal(options, sharedState) {
4429
4539
  await schedule.fn();
4430
4540
  },
4431
4541
  async emitThreadEvent(event, payload) {
4432
- const errors = [];
4433
- for (const handler of [...threadEventHandlers[event]]) {
4434
- try {
4435
- await handler(payload);
4436
- } catch (error) {
4437
- errors.push(error);
4438
- emitLog("warn", `${event} handler failed: ${errorMessage(error)}`);
4439
- }
4542
+ const { errors } = await deliverThreadEvent(event, payload);
4543
+ const settled = settledEventFor(event, payload);
4544
+ if (settled !== null) {
4545
+ errors.push(
4546
+ ...(await deliverThreadEvent("experimental_thread.settled", settled)).errors
4547
+ );
4440
4548
  }
4441
4549
  return { errors };
4442
4550
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@get-bb/plugin-sdk",
3
- "version": "0.6.157",
3
+ "version": "0.6.164",
4
4
  "license": "MIT",
5
5
  "homepage": "https://github.com/get-bb/bb#readme",
6
6
  "bugs": {
@@ -99,6 +99,12 @@
99
99
  "import": "./dist/internal/thread-status.js",
100
100
  "default": "./dist/internal/thread-status.js"
101
101
  },
102
+ "./internal/thread-event-gate": {
103
+ "source": "./src/internal/thread-event-gate.ts",
104
+ "types": "./bundled-types/bb-plugin-sdk-internal-thread-event-gate.d.ts",
105
+ "import": "./dist/internal/thread-event-gate.js",
106
+ "default": "./dist/internal/thread-event-gate.js"
107
+ },
102
108
  "./internal/file-navigation-validation": {
103
109
  "source": "./src/internal/file-navigation-validation.ts",
104
110
  "types": "./bundled-types/bb-plugin-sdk-internal-file-navigation-validation.d.ts",
@@ -180,6 +186,7 @@
180
186
  "@bb/server-contract": "workspace:*",
181
187
  "@bb/skill-index": "workspace:*",
182
188
  "@bb/test-helpers": "workspace:*",
189
+ "@bb/text-utils": "workspace:*",
183
190
  "@bb/tsconfig": "workspace:*",
184
191
  "@testing-library/react": "^16.3.3",
185
192
  "@types/better-sqlite3": "^7.6.13",