@standardagents/builder 0.11.0-next.41deba4 → 0.11.0-next.5d2e71b

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/dist/index.d.ts CHANGED
@@ -240,6 +240,10 @@ interface ThreadInstance {
240
240
  }>;
241
241
  getLogs(limit?: number, offset?: number, order?: "asc" | "desc"): Promise<LogData[]>;
242
242
  getThreadMeta(threadId: string): Promise<ThreadMetadata | null>;
243
+ deleteMessage(messageId: string): Promise<{
244
+ success: boolean;
245
+ error?: string;
246
+ }>;
243
247
  shouldStop(): Promise<boolean>;
244
248
  tools(): Record<string, () => Promise<NativeToolModule>>;
245
249
  hooks(): HookRegistry;
@@ -264,6 +268,7 @@ interface ThreadInstance {
264
268
  data?: string;
265
269
  error?: string;
266
270
  }>;
271
+ runAgent(threadId: string, agentName: string): Promise<void>;
267
272
  scheduleEffect(threadId: string, effectName: string, effectArgs: Record<string, unknown>, delayMs?: number): Promise<string>;
268
273
  getScheduledEffects(name?: string): Promise<Array<{
269
274
  id: string;
@@ -1066,6 +1071,16 @@ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableOb
1066
1071
  * Used for creating ThreadState outside of flow execution.
1067
1072
  */
1068
1073
  getThreadMetadata(threadId: string): Promise<ThreadMetadata>;
1074
+ /**
1075
+ * Trigger an agent to run on this thread.
1076
+ *
1077
+ * Queues an agent execution via the alarm queue. The execution
1078
+ * runs asynchronously in the background.
1079
+ *
1080
+ * @param threadId - Thread ID for the execution
1081
+ * @param agentName - Name of the agent to run
1082
+ */
1083
+ runAgent(threadId: string, agentName: string): Promise<void>;
1069
1084
  /**
1070
1085
  * Schedule an effect for future execution.
1071
1086
  *
package/dist/index.js CHANGED
@@ -2,7 +2,6 @@ import { sip } from '@standardagents/sip';
2
2
  import fs2 from 'fs';
3
3
  import path3 from 'path';
4
4
  import { fileURLToPath } from 'url';
5
- import { createRequire } from 'module';
6
5
  export { defineAgent, defineHook, defineModel, definePrompt, defineThreadEndpoint, defineTool } from '@standardagents/spec';
7
6
  import { DurableObject } from 'cloudflare:workers';
8
7
 
@@ -1996,7 +1995,7 @@ async function getMessages(flow, limit = 100, offset = 0, order = "asc") {
1996
1995
  parent_id,
1997
1996
  depth
1998
1997
  FROM messages
1999
- ORDER BY created_at ${orderClause}
1998
+ ORDER BY created_at ${orderClause}, rowid ${orderClause}
2000
1999
  LIMIT ? OFFSET ?`,
2001
2000
  limit,
2002
2001
  offset
@@ -2312,6 +2311,10 @@ var init_ThreadStateImpl = __esm({
2312
2311
  async updateMessage(messageId, updates) {
2313
2312
  throw new Error("updateMessage not yet implemented");
2314
2313
  }
2314
+ async deleteMessage(messageId) {
2315
+ const result = await this._threadInstance.deleteMessage(messageId);
2316
+ return result.success;
2317
+ }
2315
2318
  // ─────────────────────────────────────────────────────────────────────────
2316
2319
  // Logs
2317
2320
  // ─────────────────────────────────────────────────────────────────────────
@@ -2496,6 +2499,12 @@ var init_ThreadStateImpl = __esm({
2496
2499
  return this._executionState;
2497
2500
  }
2498
2501
  // ─────────────────────────────────────────────────────────────────────────
2502
+ // Agent Execution
2503
+ // ─────────────────────────────────────────────────────────────────────────
2504
+ async runAgent(agentName) {
2505
+ await this._threadInstance.runAgent(this._metadata.id, agentName);
2506
+ }
2507
+ // ─────────────────────────────────────────────────────────────────────────
2499
2508
  // Effect Scheduling
2500
2509
  // ─────────────────────────────────────────────────────────────────────────
2501
2510
  async scheduleEffect(name, args, delay = 0) {
@@ -5824,14 +5833,14 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
5824
5833
  ${columns.join(", ")}
5825
5834
  FROM messages
5826
5835
  WHERE parent_id IS NULL
5827
- ORDER BY created_at ASC
5836
+ ORDER BY created_at ASC, rowid ASC
5828
5837
  `;
5829
5838
  const cursor = await storage.sql.exec(query);
5830
5839
  rows = cursor.toArray();
5831
5840
  }
5832
5841
  if (state.extraMessages && state.extraMessages.length > 0) {
5833
5842
  rows.push(...state.extraMessages);
5834
- rows.sort((a, b) => a.created_at - b.created_at);
5843
+ rows.sort((a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
5835
5844
  }
5836
5845
  const messages = rows.map((row) => ({
5837
5846
  id: row.id,
@@ -7688,7 +7697,6 @@ function validateAgentData(data) {
7688
7697
  }
7689
7698
 
7690
7699
  // src/plugin.ts
7691
- createRequire(import.meta.url);
7692
7700
  var VIRTUAL_TOOLS_ID = "virtual:@standardagents-tools";
7693
7701
  var RESOLVED_VIRTUAL_TOOLS_ID = "\0" + VIRTUAL_TOOLS_ID;
7694
7702
  var VIRTUAL_ROUTES_ID = "virtual:@standardagents-routes";
@@ -8141,7 +8149,15 @@ function agentbuilder(options = {}) {
8141
8149
  "zod",
8142
8150
  "openai"
8143
8151
  ];
8152
+ const currentDir = path3.dirname(fileURLToPath(import.meta.url));
8153
+ const isInDist = currentDir.endsWith("dist");
8154
+ const builderClientDir = path3.resolve(
8155
+ currentDir,
8156
+ isInDist ? "./client" : "../dist/client"
8157
+ );
8144
8158
  return {
8159
+ // Set publicDir to builder's client assets so Cloudflare plugin preserves assets config
8160
+ publicDir: fs2.existsSync(builderClientDir) ? builderClientDir : void 0,
8145
8161
  optimizeDeps: {
8146
8162
  // Exclude our packages from pre-bundling - they contain cloudflare:workers imports
8147
8163
  // that cannot be resolved during dependency optimization
@@ -8295,6 +8311,22 @@ function isPublicRoute(routePath) {
8295
8311
  return false;
8296
8312
  }
8297
8313
 
8314
+ // CORS headers for API responses
8315
+ const CORS_HEADERS = {
8316
+ "Access-Control-Allow-Origin": "*",
8317
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
8318
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
8319
+ "Access-Control-Max-Age": "86400",
8320
+ };
8321
+
8322
+ // Helper to create headers with CORS
8323
+ function corsHeaders(contentType) {
8324
+ return {
8325
+ "Content-Type": contentType,
8326
+ ...CORS_HEADERS,
8327
+ };
8328
+ }
8329
+
8298
8330
  export async function router(request, env) {
8299
8331
  const url = new URL(request.url);
8300
8332
  const pathname = url.pathname;
@@ -8304,6 +8336,14 @@ export async function router(request, env) {
8304
8336
  return null;
8305
8337
  }
8306
8338
 
8339
+ // Handle CORS preflight requests
8340
+ if (request.method === "OPTIONS") {
8341
+ return new Response(null, {
8342
+ status: 204,
8343
+ headers: CORS_HEADERS,
8344
+ });
8345
+ }
8346
+
8307
8347
  // Strip mount point prefix for route matching, ensuring we keep the leading slash
8308
8348
  let routePath = pathname.slice(MOUNT_POINT.length) || "/";
8309
8349
  if (!routePath.startsWith('/')) {
@@ -8357,16 +8397,21 @@ ${threadRouteCode}
8357
8397
  const result = await controller(context);
8358
8398
 
8359
8399
  if (result instanceof Response) {
8400
+ // Return Response objects as-is - CORS headers can't be safely added
8401
+ // to Response objects in the workerd environment without issues.
8402
+ // Controllers that return streaming/binary responses should add
8403
+ // CORS headers themselves if needed.
8360
8404
  return result;
8361
8405
  }
8362
8406
  if (typeof result === "string") {
8363
8407
  return new Response(result, {
8364
- headers: {
8365
- "Content-Type": "text/plain",
8366
- },
8408
+ headers: corsHeaders("text/plain"),
8367
8409
  });
8368
8410
  }
8369
- return Response.json(result);
8411
+ // JSON responses get CORS headers
8412
+ return new Response(JSON.stringify(result), {
8413
+ headers: corsHeaders("application/json"),
8414
+ });
8370
8415
  }
8371
8416
 
8372
8417
  // Serve UI for all other routes (SPA fallback)
@@ -8381,13 +8426,15 @@ async function serveUI(pathname, env) {
8381
8426
  // Create a proper request for the asset path
8382
8427
  // Use a dummy origin since we only care about the path
8383
8428
  // Re-add mount point since pathname was stripped by router
8384
- const assetUrl = \`http://localhost\${MOUNT_POINT}\${pathname}\`;
8429
+ // Handle root mountPoint "/" specially to avoid double slashes
8430
+ const mountPrefix = MOUNT_POINT === "/" ? "" : MOUNT_POINT;
8431
+ const assetUrl = \`http://localhost\${mountPrefix}\${pathname}\`;
8385
8432
  let response = await env.ASSETS.fetch(assetUrl);
8386
8433
 
8387
8434
  // If not found, fall back to index.html for SPA routing
8388
8435
  const isIndexHtml = response.status === 404 || pathname === "/" || !pathname.includes(".");
8389
8436
  if (isIndexHtml) {
8390
- response = await env.ASSETS.fetch(\`http://localhost\${MOUNT_POINT}/index.html\`);
8437
+ response = await env.ASSETS.fetch(\`http://localhost\${mountPrefix}/index.html\`);
8391
8438
 
8392
8439
  // Transform HTML to use configured mount point
8393
8440
  if (response.status === 200) {
@@ -8672,7 +8719,8 @@ import { DurableAgentBuilder as _BaseDurableAgentBuilder } from '@standardagents
8672
8719
 
8673
8720
  // Import sip WASM module and initializer
8674
8721
  // Static import allows workerd to pre-compile the WASM at bundle time
8675
- import _sipWasm from '@standardagents/sip/dist/sip.wasm';
8722
+ // WASM is bundled in builder's dist to avoid transitive dependency resolution issues
8723
+ import _sipWasm from '@standardagents/builder/dist/sip.wasm';
8676
8724
  import { initWithWasmModule as _initSipWasm } from '@standardagents/sip';
8677
8725
 
8678
8726
  // Re-export router from virtual:@standardagents-routes
@@ -9227,6 +9275,13 @@ export class DurableAgentBuilder extends _BaseDurableAgentBuilder {
9227
9275
  const items = match[1].match(/['"]([^'"]+)['"]/g);
9228
9276
  return items ? items.map((s) => s.replace(/['"]/g, "")) : [];
9229
9277
  };
9278
+ const getSidePrompt = (c, side) => {
9279
+ const sideRegex = new RegExp(`${side}:\\s*\\{([^}]+)\\}`, "s");
9280
+ const sideMatch = c.match(sideRegex);
9281
+ if (!sideMatch) return null;
9282
+ const promptMatch = sideMatch[1].match(/prompt:\s*['"]([^'"]+)['"]/);
9283
+ return promptMatch ? promptMatch[1] : null;
9284
+ };
9230
9285
  const name = getName(content);
9231
9286
  if (!name) return null;
9232
9287
  return {
@@ -9237,6 +9292,8 @@ export class DurableAgentBuilder extends _BaseDurableAgentBuilder {
9237
9292
  default_prompt: getDefaultPrompt(content) || "",
9238
9293
  default_model: getDefaultModel(content) || "",
9239
9294
  tools: getTools(content),
9295
+ side_a_agent_prompt: getSidePrompt(content, "sideA"),
9296
+ side_b_agent_prompt: getSidePrompt(content, "sideB"),
9240
9297
  created_at: Math.floor(Date.now() / 1e3)
9241
9298
  };
9242
9299
  } catch (error) {
@@ -10659,6 +10716,33 @@ var DurableThread = class extends DurableObject {
10659
10716
  };
10660
10717
  }
10661
10718
  // ============================================================
10719
+ // Agent Execution Methods (for use by ThreadStateImpl)
10720
+ // ============================================================
10721
+ /**
10722
+ * Trigger an agent to run on this thread.
10723
+ *
10724
+ * Queues an agent execution via the alarm queue. The execution
10725
+ * runs asynchronously in the background.
10726
+ *
10727
+ * @param threadId - Thread ID for the execution
10728
+ * @param agentName - Name of the agent to run
10729
+ */
10730
+ async runAgent(threadId, agentName) {
10731
+ const agents = this.agents();
10732
+ if (!agents[agentName]) {
10733
+ throw new Error(`Agent not found: ${agentName}`);
10734
+ }
10735
+ await this.alarmQueue.enqueue(
10736
+ "executeFlow",
10737
+ {
10738
+ threadId,
10739
+ agentId: agentName
10740
+ },
10741
+ 0
10742
+ // Execute immediately
10743
+ );
10744
+ }
10745
+ // ============================================================
10662
10746
  // Effect Scheduling Methods (for use by ThreadStateImpl)
10663
10747
  // ============================================================
10664
10748
  /**
@@ -11025,7 +11109,7 @@ var DurableThread = class extends DurableObject {
11025
11109
  SELECT id, role, content, name, tool_calls, tool_call_id, tool_status, log_id, created_at, silent, parent_id, depth, status, reasoning_content, reasoning_details, attachments
11026
11110
  FROM messages
11027
11111
  ${whereClause}
11028
- ORDER BY created_at ${order === "ASC" ? "ASC" : "DESC"}
11112
+ ORDER BY created_at ${order === "ASC" ? "ASC" : "DESC"}, rowid ${order === "ASC" ? "ASC" : "DESC"}
11029
11113
  LIMIT ? OFFSET ?
11030
11114
  `,
11031
11115
  limit,
@@ -13581,7 +13665,7 @@ var FlowStateSdk = class _FlowStateSdk {
13581
13665
  parent_id,
13582
13666
  depth
13583
13667
  FROM messages
13584
- ORDER BY created_at ${orderClause}
13668
+ ORDER BY created_at ${orderClause}, rowid ${orderClause}
13585
13669
  LIMIT ? OFFSET ?`,
13586
13670
  limit,
13587
13671
  offset