llmist 9.1.2 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1260,7 +1260,11 @@ var init_messages = __esm({
1260
1260
  parts.push("\n=================\n");
1261
1261
  for (const gadget of gadgets) {
1262
1262
  const gadgetName = gadget.name ?? gadget.constructor.name;
1263
- const instruction = gadget.getInstruction(this.argPrefix);
1263
+ const instruction = gadget.getInstruction({
1264
+ argPrefix: this.argPrefix,
1265
+ startPrefix: this.startPrefix,
1266
+ endPrefix: this.endPrefix
1267
+ });
1264
1268
  const schemaMarker = "\n\nInput Schema (BLOCK):";
1265
1269
  const schemaIndex = instruction.indexOf(schemaMarker);
1266
1270
  const description = (schemaIndex !== -1 ? instruction.substring(0, schemaIndex) : instruction).trim();
@@ -6004,13 +6008,13 @@ var init_openai = __esm({
6004
6008
  async generateSpeech(options) {
6005
6009
  const client = this.client;
6006
6010
  const spec = getOpenAISpeechModelSpec(options.model);
6007
- const format = options.responseFormat ?? spec?.defaultFormat ?? "mp3";
6011
+ const format2 = options.responseFormat ?? spec?.defaultFormat ?? "mp3";
6008
6012
  const voice = options.voice ?? spec?.defaultVoice ?? "alloy";
6009
6013
  const response = await client.audio.speech.create({
6010
6014
  model: options.model,
6011
6015
  input: options.input,
6012
6016
  voice,
6013
- response_format: format,
6017
+ response_format: format2,
6014
6018
  speed: options.speed ?? 1
6015
6019
  });
6016
6020
  const audioBuffer = await response.arrayBuffer();
@@ -6022,7 +6026,7 @@ var init_openai = __esm({
6022
6026
  characterCount: options.input.length
6023
6027
  },
6024
6028
  cost,
6025
- format
6029
+ format: format2
6026
6030
  };
6027
6031
  }
6028
6032
  buildApiRequest(options, descriptor, spec, messages) {
@@ -11847,17 +11851,17 @@ init_gadget_output_store();
11847
11851
  // src/agent/hints.ts
11848
11852
  init_prompt_config();
11849
11853
  function iterationProgressHint(options) {
11850
- const { timing = "always", showUrgency = true, template } = options ?? {};
11854
+ const { timing: timing2 = "always", showUrgency = true, template } = options ?? {};
11851
11855
  return {
11852
11856
  controllers: {
11853
11857
  beforeLLMCall: async (ctx) => {
11854
11858
  const iteration = ctx.iteration + 1;
11855
11859
  const maxIterations = ctx.maxIterations;
11856
11860
  const progress = iteration / maxIterations;
11857
- if (timing === "late" && progress < 0.5) {
11861
+ if (timing2 === "late" && progress < 0.5) {
11858
11862
  return { action: "proceed" };
11859
11863
  }
11860
- if (timing === "urgent" && progress < 0.8) {
11864
+ if (timing2 === "urgent" && progress < 0.8) {
11861
11865
  return { action: "proceed" };
11862
11866
  }
11863
11867
  const remaining = maxIterations - iteration;
@@ -12018,6 +12022,24 @@ init_typed_gadget();
12018
12022
 
12019
12023
  // src/gadgets/helpers.ts
12020
12024
  init_input_content();
12025
+ function gadgetSuccess(data = {}) {
12026
+ return JSON.stringify({ success: true, ...data });
12027
+ }
12028
+ function gadgetError(message, details) {
12029
+ return JSON.stringify({ error: message, ...details });
12030
+ }
12031
+ function getErrorMessage(error) {
12032
+ return error instanceof Error ? error.message : String(error);
12033
+ }
12034
+ function withErrorHandling(execute) {
12035
+ return async (params, ctx) => {
12036
+ try {
12037
+ return await execute(params, ctx);
12038
+ } catch (error) {
12039
+ return gadgetError(getErrorMessage(error));
12040
+ }
12041
+ };
12042
+ }
12021
12043
  function createMediaOutput(kind, data, mimeType, options) {
12022
12044
  const buffer = data instanceof Buffer ? data : Buffer.from(data);
12023
12045
  return {
@@ -12213,7 +12235,313 @@ init_anthropic();
12213
12235
  init_discovery();
12214
12236
  init_gemini();
12215
12237
  init_openai();
12238
+
12239
+ // src/utils/format.ts
12240
+ function truncate(text3, maxLength, suffix = "...") {
12241
+ if (text3.length <= maxLength) return text3;
12242
+ const truncateAt = maxLength - suffix.length;
12243
+ if (truncateAt <= 0) return suffix.slice(0, maxLength);
12244
+ return text3.slice(0, truncateAt) + suffix;
12245
+ }
12246
+ function formatBytes(bytes, decimals = 1) {
12247
+ if (bytes === 0) return "0 B";
12248
+ const k = 1024;
12249
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
12250
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
12251
+ const size = bytes / Math.pow(k, i);
12252
+ const formatted = size % 1 === 0 ? size.toString() : size.toFixed(decimals);
12253
+ return `${formatted} ${sizes[i]}`;
12254
+ }
12255
+ function formatDate(isoDate, options = {
12256
+ year: "numeric",
12257
+ month: "short",
12258
+ day: "numeric",
12259
+ hour: "2-digit",
12260
+ minute: "2-digit"
12261
+ }) {
12262
+ try {
12263
+ const date = new Date(isoDate);
12264
+ return date.toLocaleString(void 0, options);
12265
+ } catch {
12266
+ return isoDate;
12267
+ }
12268
+ }
12269
+ function formatDuration(ms, options = {}) {
12270
+ if (ms < 1e3) {
12271
+ return `${Math.round(ms)}ms`;
12272
+ }
12273
+ const seconds = Math.floor(ms / 1e3);
12274
+ const minutes = Math.floor(seconds / 60);
12275
+ const hours = Math.floor(minutes / 60);
12276
+ if (hours > 0) {
12277
+ const remainingMinutes = minutes % 60;
12278
+ const remainingSeconds = seconds % 60;
12279
+ if (options.compact) {
12280
+ return `${hours}h ${remainingMinutes}m`;
12281
+ }
12282
+ return remainingSeconds > 0 ? `${hours}h ${remainingMinutes}m ${remainingSeconds}s` : `${hours}h ${remainingMinutes}m`;
12283
+ }
12284
+ if (minutes > 0) {
12285
+ const remainingSeconds = seconds % 60;
12286
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
12287
+ }
12288
+ const secs = ms / 1e3;
12289
+ return secs % 1 === 0 ? `${secs}s` : `${secs.toFixed(1)}s`;
12290
+ }
12291
+ var format = {
12292
+ truncate,
12293
+ bytes: formatBytes,
12294
+ date: formatDate,
12295
+ duration: formatDuration
12296
+ };
12297
+
12298
+ // src/utils/timing.ts
12299
+ function randomDelay(min, max) {
12300
+ return Math.floor(Math.random() * (max - min + 1)) + min;
12301
+ }
12302
+ async function humanDelay(min = 50, max = 150) {
12303
+ const delay = randomDelay(min, max);
12304
+ return new Promise((resolve) => setTimeout(resolve, delay));
12305
+ }
12306
+ async function withTimeout(fn, timeoutMs, signal) {
12307
+ return new Promise((resolve, reject) => {
12308
+ if (signal?.aborted) {
12309
+ reject(new Error("Operation aborted"));
12310
+ return;
12311
+ }
12312
+ let settled = false;
12313
+ const timeoutId = setTimeout(() => {
12314
+ if (!settled) {
12315
+ settled = true;
12316
+ reject(new Error(`Operation timed out after ${timeoutMs}ms`));
12317
+ }
12318
+ }, timeoutMs);
12319
+ const abortHandler = () => {
12320
+ if (!settled) {
12321
+ settled = true;
12322
+ clearTimeout(timeoutId);
12323
+ reject(new Error("Operation aborted"));
12324
+ }
12325
+ };
12326
+ signal?.addEventListener("abort", abortHandler);
12327
+ fn().then((result) => {
12328
+ if (!settled) {
12329
+ settled = true;
12330
+ clearTimeout(timeoutId);
12331
+ signal?.removeEventListener("abort", abortHandler);
12332
+ resolve(result);
12333
+ }
12334
+ }).catch((error) => {
12335
+ if (!settled) {
12336
+ settled = true;
12337
+ clearTimeout(timeoutId);
12338
+ signal?.removeEventListener("abort", abortHandler);
12339
+ reject(error);
12340
+ }
12341
+ });
12342
+ });
12343
+ }
12344
+ async function withRetry(fn, options = {}) {
12345
+ const {
12346
+ maxRetries = 3,
12347
+ delay = 1e3,
12348
+ backoff = "exponential",
12349
+ maxDelay = 3e4,
12350
+ shouldRetry = () => true,
12351
+ onRetry
12352
+ } = options;
12353
+ let lastError;
12354
+ let currentDelay = delay;
12355
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
12356
+ try {
12357
+ return await fn();
12358
+ } catch (error) {
12359
+ lastError = error;
12360
+ if (attempt >= maxRetries || !shouldRetry(error, attempt)) {
12361
+ throw error;
12362
+ }
12363
+ const waitTime = Math.min(currentDelay, maxDelay);
12364
+ onRetry?.(error, attempt + 1, waitTime);
12365
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
12366
+ if (backoff === "exponential") {
12367
+ currentDelay *= 2;
12368
+ } else {
12369
+ currentDelay += delay;
12370
+ }
12371
+ }
12372
+ }
12373
+ throw lastError;
12374
+ }
12375
+ var timing = {
12376
+ randomDelay,
12377
+ humanDelay,
12378
+ withTimeout,
12379
+ withRetry
12380
+ };
12381
+
12382
+ // src/session/manager.ts
12383
+ var BaseSessionManager = class {
12384
+ /** Map of session ID to session object */
12385
+ sessions = /* @__PURE__ */ new Map();
12386
+ /** Counter for generating unique session IDs */
12387
+ idCounter = 0;
12388
+ /**
12389
+ * Generate a unique session ID with the given prefix.
12390
+ *
12391
+ * @param prefix - Prefix for the ID (e.g., "p" for pages, "b" for browsers)
12392
+ * @returns Unique ID like "p1", "p2", etc.
12393
+ */
12394
+ generateId(prefix) {
12395
+ return `${prefix}${++this.idCounter}`;
12396
+ }
12397
+ /**
12398
+ * Get a session by ID.
12399
+ */
12400
+ getSession(id) {
12401
+ return this.sessions.get(id);
12402
+ }
12403
+ /**
12404
+ * Get a session by ID, throwing if not found.
12405
+ */
12406
+ requireSession(id) {
12407
+ const session = this.sessions.get(id);
12408
+ if (!session) {
12409
+ throw new Error(`Session not found: ${id}`);
12410
+ }
12411
+ return session;
12412
+ }
12413
+ /**
12414
+ * List all active session IDs.
12415
+ */
12416
+ listSessions() {
12417
+ return Array.from(this.sessions.keys());
12418
+ }
12419
+ /**
12420
+ * Check if a session exists.
12421
+ */
12422
+ hasSession(id) {
12423
+ return this.sessions.has(id);
12424
+ }
12425
+ /**
12426
+ * Close all sessions.
12427
+ * Closes sessions in reverse order (most recent first).
12428
+ */
12429
+ async closeAll() {
12430
+ const ids = this.listSessions().reverse();
12431
+ for (const id of ids) {
12432
+ try {
12433
+ await this.closeSession(id);
12434
+ } catch {
12435
+ }
12436
+ }
12437
+ }
12438
+ };
12439
+ var SimpleSessionManager = class extends BaseSessionManager {
12440
+ /**
12441
+ * Create a session by storing the provided data.
12442
+ */
12443
+ async createSession(data) {
12444
+ const id = this.generateId("s");
12445
+ if (data !== void 0) {
12446
+ this.sessions.set(id, data);
12447
+ }
12448
+ return id;
12449
+ }
12450
+ /**
12451
+ * Close a session by removing it from the map.
12452
+ */
12453
+ async closeSession(id) {
12454
+ this.sessions.delete(id);
12455
+ }
12456
+ /**
12457
+ * Set session data directly.
12458
+ */
12459
+ setSession(id, data) {
12460
+ this.sessions.set(id, data);
12461
+ }
12462
+ };
12463
+
12464
+ // src/agent/subagent.ts
12216
12465
  function getHostExports(ctx) {
12466
+ if (!ctx?.hostExports) {
12467
+ throw new Error(
12468
+ "hostExports not available. Subagent gadgets must be run via llmist agent. Ensure you are using llmist >= 6.2.0 and running through the CLI or AgentBuilder."
12469
+ );
12470
+ }
12471
+ return ctx.hostExports;
12472
+ }
12473
+ function createSubagent(ctx, options) {
12474
+ const {
12475
+ name,
12476
+ gadgets,
12477
+ systemPrompt,
12478
+ model: runtimeModel,
12479
+ defaultModel = "sonnet",
12480
+ maxIterations: runtimeMaxIterations,
12481
+ defaultMaxIterations = 15,
12482
+ hooks,
12483
+ temperature
12484
+ } = options;
12485
+ const { AgentBuilder: AgentBuilder2, LLMist: LLMist2 } = getHostExports(ctx);
12486
+ const client = new LLMist2();
12487
+ const model = resolveSubagentModel(ctx, name, runtimeModel, defaultModel);
12488
+ const maxIterations = resolveValue(ctx, name, {
12489
+ runtime: runtimeMaxIterations,
12490
+ subagentKey: "maxIterations",
12491
+ defaultValue: defaultMaxIterations
12492
+ });
12493
+ let builder = new AgentBuilder2(client).withModel(model).withGadgets(...gadgets).withMaxIterations(maxIterations).withParentContext(ctx);
12494
+ if (systemPrompt) {
12495
+ builder = builder.withSystem(systemPrompt);
12496
+ }
12497
+ if (hooks) {
12498
+ builder = builder.withHooks(hooks);
12499
+ }
12500
+ if (temperature !== void 0) {
12501
+ builder = builder.withTemperature(temperature);
12502
+ }
12503
+ if (ctx.logger) {
12504
+ builder = builder.withLogger(ctx.logger);
12505
+ }
12506
+ return builder;
12507
+ }
12508
+ function hasHostExports(ctx) {
12509
+ return ctx?.hostExports !== void 0;
12510
+ }
12511
+
12512
+ // src/package/manifest.ts
12513
+ function parseManifest(packageJson) {
12514
+ const llmist = packageJson.llmist;
12515
+ if (!llmist || typeof llmist !== "object") {
12516
+ return void 0;
12517
+ }
12518
+ return llmist;
12519
+ }
12520
+ function hasPreset(manifest, presetName) {
12521
+ return manifest?.presets?.[presetName] !== void 0;
12522
+ }
12523
+ function getPresetGadgets(manifest, presetName) {
12524
+ const preset = manifest?.presets?.[presetName];
12525
+ if (preset === void 0) return void 0;
12526
+ return preset;
12527
+ }
12528
+ function hasSubagents(manifest) {
12529
+ return manifest?.subagents !== void 0 && Object.keys(manifest.subagents).length > 0;
12530
+ }
12531
+ function getSubagent(manifest, name) {
12532
+ return manifest?.subagents?.[name];
12533
+ }
12534
+ function listSubagents(manifest) {
12535
+ if (!manifest?.subagents) return [];
12536
+ return Object.keys(manifest.subagents);
12537
+ }
12538
+ function listPresets(manifest) {
12539
+ if (!manifest?.presets) return [];
12540
+ return Object.keys(manifest.presets);
12541
+ }
12542
+
12543
+ // src/index.ts
12544
+ function getHostExports2(ctx) {
12217
12545
  if (!ctx?.hostExports) {
12218
12546
  throw new Error(
12219
12547
  "hostExports not available. Gadgets that create subagents must be run via llmist agent, not standalone. Ensure you are using llmist >= 6.2.0."
@@ -12227,6 +12555,7 @@ export {
12227
12555
  Agent,
12228
12556
  AgentBuilder,
12229
12557
  AnthropicMessagesProvider,
12558
+ BaseSessionManager,
12230
12559
  CompactionManager,
12231
12560
  ConversationManager,
12232
12561
  DEFAULT_COMPACTION_CONFIG,
@@ -12255,6 +12584,7 @@ export {
12255
12584
  ModelIdentifierParser,
12256
12585
  ModelRegistry,
12257
12586
  OpenAIChatProvider,
12587
+ SimpleSessionManager,
12258
12588
  SlidingWindowStrategy,
12259
12589
  StreamProcessor,
12260
12590
  SummarizationStrategy,
@@ -12273,6 +12603,7 @@ export {
12273
12603
  createLogger,
12274
12604
  createMediaOutput,
12275
12605
  createOpenAIProviderFromEnv,
12606
+ createSubagent,
12276
12607
  defaultLogger,
12277
12608
  detectAudioMimeType,
12278
12609
  detectImageMimeType,
@@ -12281,12 +12612,25 @@ export {
12281
12612
  filterByDepth,
12282
12613
  filterByParent,
12283
12614
  filterRootEvents,
12615
+ format,
12616
+ formatBytes,
12617
+ formatDate,
12618
+ formatDuration,
12284
12619
  formatLLMError,
12285
- getHostExports,
12620
+ gadgetError,
12621
+ gadgetSuccess,
12622
+ getErrorMessage,
12623
+ getHostExports2 as getHostExports,
12286
12624
  getModelId,
12625
+ getPresetGadgets,
12287
12626
  getProvider,
12627
+ getSubagent,
12288
12628
  groupByParent,
12629
+ hasHostExports,
12630
+ hasPreset,
12289
12631
  hasProviderPrefix,
12632
+ hasSubagents,
12633
+ humanDelay,
12290
12634
  imageFromBase64,
12291
12635
  imageFromBuffer,
12292
12636
  imageFromUrl,
@@ -12301,9 +12645,13 @@ export {
12301
12645
  isSubagentEvent,
12302
12646
  isTextPart,
12303
12647
  iterationProgressHint,
12648
+ listPresets,
12649
+ listSubagents,
12304
12650
  normalizeMessageContent,
12305
12651
  parallelGadgetHint,
12306
12652
  parseDataUrl,
12653
+ parseManifest,
12654
+ randomDelay,
12307
12655
  resolveConfig,
12308
12656
  resolveHintTemplate,
12309
12657
  resolveModel,
@@ -12321,10 +12669,15 @@ export {
12321
12669
  schemaToJSONSchema,
12322
12670
  stream,
12323
12671
  text,
12672
+ timing,
12324
12673
  toBase64,
12674
+ truncate,
12325
12675
  validateAndApplyDefaults,
12326
12676
  validateGadgetParams,
12327
12677
  validateGadgetSchema,
12678
+ withErrorHandling,
12679
+ withRetry,
12680
+ withTimeout,
12328
12681
  z5 as z
12329
12682
  };
12330
12683
  //# sourceMappingURL=index.js.map