@promptbook/wizard 0.110.0 → 0.111.0-1

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.
Files changed (33) hide show
  1. package/README.md +4 -0
  2. package/esm/index.es.js +677 -171
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/src/_packages/utils.index.d.ts +12 -0
  5. package/esm/typings/src/book-2.0/agent-source/BookEditable.d.ts +41 -0
  6. package/esm/typings/src/book-2.0/agent-source/CreateAgentModelRequirementsOptions.d.ts +5 -0
  7. package/esm/typings/src/book-components/Chat/Chat/ImagePromptRenderer.d.ts +21 -0
  8. package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +5 -0
  9. package/esm/typings/src/book-components/Chat/LlmChat/defaults.d.ts +9 -0
  10. package/esm/typings/src/book-components/Chat/hooks/useChatActionsOverlap.d.ts +6 -0
  11. package/esm/typings/src/book-components/Chat/save/_common/ChatSaveFormatDefinition.d.ts +7 -1
  12. package/esm/typings/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +6 -5
  13. package/esm/typings/src/book-components/Chat/save/index.d.ts +3 -3
  14. package/esm/typings/src/book-components/Chat/save/pdf/buildChatPdf.d.ts +11 -0
  15. package/esm/typings/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +2 -2
  16. package/esm/typings/src/book-components/Chat/utils/parseImagePrompts.d.ts +42 -0
  17. package/esm/typings/src/book-components/Chat/utils/parseImagePrompts.test.d.ts +1 -0
  18. package/esm/typings/src/commitments/MEMORY/MEMORY.d.ts +67 -0
  19. package/esm/typings/src/commitments/MEMORY/MEMORY.test.d.ts +1 -0
  20. package/esm/typings/src/commitments/USE_IMAGE_GENERATOR/USE_IMAGE_GENERATOR.d.ts +3 -12
  21. package/esm/typings/src/commitments/_common/toolRuntimeContext.d.ts +49 -0
  22. package/esm/typings/src/constants/streaming.d.ts +20 -0
  23. package/esm/typings/src/llm-providers/openai/utils/buildToolInvocationScript.d.ts +9 -0
  24. package/esm/typings/src/utils/clientVersion.d.ts +51 -0
  25. package/esm/typings/src/utils/knowledge/inlineKnowledgeSource.d.ts +13 -9
  26. package/esm/typings/src/utils/knowledge/simplifyKnowledgeLabel.d.ts +20 -0
  27. package/esm/typings/src/utils/knowledge/simplifyKnowledgeLabel.test.d.ts +1 -0
  28. package/esm/typings/src/utils/normalization/constructImageFilename.d.ts +18 -0
  29. package/esm/typings/src/utils/normalization/constructImageFilename.test.d.ts +1 -0
  30. package/esm/typings/src/version.d.ts +1 -1
  31. package/package.json +2 -2
  32. package/umd/index.umd.js +677 -171
  33. package/umd/index.umd.js.map +1 -1
package/esm/index.es.js CHANGED
@@ -38,7 +38,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
38
38
  * @generated
39
39
  * @see https://github.com/webgptorg/promptbook
40
40
  */
41
- const PROMPTBOOK_ENGINE_VERSION = '0.110.0';
41
+ const PROMPTBOOK_ENGINE_VERSION = '0.111.0-1';
42
42
  /**
43
43
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
44
44
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -6567,6 +6567,36 @@ function prompt(strings, ...values) {
6567
6567
  * Note: [💞] Ignore a discrepancy between file name and entity name
6568
6568
  */
6569
6569
 
6570
+ /**
6571
+ * HTTP header used by Promptbook clients to advertise their release version.
6572
+ *
6573
+ * @public exported from `@promptbook/utils`
6574
+ */
6575
+ const CLIENT_VERSION_HEADER = 'x-promptbook-client-version';
6576
+ /**
6577
+ * The latest client (engine) version that the server expects.
6578
+ *
6579
+ * @public exported from `@promptbook/utils`
6580
+ */
6581
+ const CLIENT_LATEST_VERSION = PROMPTBOOK_ENGINE_VERSION;
6582
+ /**
6583
+ * Creates a headers object that includes the client version header.
6584
+ *
6585
+ * @param headers - Optional base headers to clone.
6586
+ * @returns New headers object augmented with `CLIENT_VERSION_HEADER`.
6587
+ *
6588
+ * @public exported from `@promptbook/utils`
6589
+ */
6590
+ function attachClientVersionHeader(headers) {
6591
+ return {
6592
+ ...(headers !== null && headers !== void 0 ? headers : {}),
6593
+ [CLIENT_VERSION_HEADER]: CLIENT_LATEST_VERSION,
6594
+ };
6595
+ }
6596
+ /**
6597
+ * Note: [💞] Ignore a discrepancy between file name and entity name
6598
+ */
6599
+
6570
6600
  /**
6571
6601
  * Detects if the code is running in a Node.js environment
6572
6602
  *
@@ -8675,6 +8705,83 @@ function mapToolsToOpenAi(tools) {
8675
8705
  }));
8676
8706
  }
8677
8707
 
8708
+ /**
8709
+ * Prompt parameter key used to pass hidden runtime context to tool execution.
8710
+ *
8711
+ * @private internal runtime wiring for commitment tools
8712
+ */
8713
+ const TOOL_RUNTIME_CONTEXT_PARAMETER = 'promptbookToolRuntimeContext';
8714
+ /**
8715
+ * Hidden argument key used to pass runtime context into individual tool calls.
8716
+ *
8717
+ * @private internal runtime wiring for commitment tools
8718
+ */
8719
+ const TOOL_RUNTIME_CONTEXT_ARGUMENT = '__promptbookToolRuntimeContext';
8720
+ /**
8721
+ * Parses unknown runtime context payload into a normalized object.
8722
+ *
8723
+ * @private internal runtime wiring for commitment tools
8724
+ */
8725
+ function parseToolRuntimeContext(rawValue) {
8726
+ if (!rawValue) {
8727
+ return null;
8728
+ }
8729
+ let parsed = rawValue;
8730
+ if (typeof rawValue === 'string') {
8731
+ try {
8732
+ parsed = JSON.parse(rawValue);
8733
+ }
8734
+ catch (_a) {
8735
+ return null;
8736
+ }
8737
+ }
8738
+ if (!parsed || typeof parsed !== 'object') {
8739
+ return null;
8740
+ }
8741
+ return parsed;
8742
+ }
8743
+ /**
8744
+ * Reads runtime context attached to tool call arguments.
8745
+ *
8746
+ * @private internal runtime wiring for commitment tools
8747
+ */
8748
+ function readToolRuntimeContextFromToolArgs(args) {
8749
+ return parseToolRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]);
8750
+ }
8751
+ /**
8752
+ * Serializes runtime context for prompt parameters.
8753
+ *
8754
+ * @private internal runtime wiring for commitment tools
8755
+ */
8756
+ function serializeToolRuntimeContext(context) {
8757
+ return JSON.stringify(context);
8758
+ }
8759
+ /**
8760
+ * Note: [💞] Ignore a discrepancy between file name and entity name
8761
+ */
8762
+
8763
+ /**
8764
+ * Builds a tool invocation script that injects hidden runtime context into tool args.
8765
+ *
8766
+ * @private utility of OpenAI tool execution wrappers
8767
+ */
8768
+ function buildToolInvocationScript(options) {
8769
+ const { functionName, functionArgsExpression } = options;
8770
+ return `
8771
+ const args = ${functionArgsExpression};
8772
+ const runtimeContextRaw =
8773
+ typeof ${TOOL_RUNTIME_CONTEXT_PARAMETER} === 'undefined'
8774
+ ? undefined
8775
+ : ${TOOL_RUNTIME_CONTEXT_PARAMETER};
8776
+
8777
+ if (runtimeContextRaw !== undefined && args && typeof args === 'object' && !Array.isArray(args)) {
8778
+ args.${TOOL_RUNTIME_CONTEXT_ARGUMENT} = runtimeContextRaw;
8779
+ }
8780
+
8781
+ return await ${functionName}(args);
8782
+ `;
8783
+ }
8784
+
8678
8785
  /**
8679
8786
  * Parses an OpenAI error message to identify which parameter is unsupported
8680
8787
  *
@@ -9028,10 +9135,10 @@ class OpenAiCompatibleExecutionTools {
9028
9135
  const scriptTool = scriptTools[0]; // <- TODO: [🧠] Which script tool to use?
9029
9136
  functionResponse = await scriptTool.execute({
9030
9137
  scriptLanguage: 'javascript',
9031
- script: `
9032
- const args = ${functionArgs};
9033
- return await ${functionName}(args);
9034
- `,
9138
+ script: buildToolInvocationScript({
9139
+ functionName,
9140
+ functionArgsExpression: functionArgs,
9141
+ }),
9035
9142
  parameters: prompt.parameters,
9036
9143
  });
9037
9144
  }
@@ -10213,28 +10320,14 @@ class OpenAiExecutionTools extends OpenAiCompatibleExecutionTools {
10213
10320
  }
10214
10321
  }
10215
10322
 
10216
- /**
10217
- * @@@
10218
- *
10219
- * @private thing of inline knowledge
10220
- */
10323
+ /** @private The default base name for inline knowledge files when the content lacks identifying text */
10221
10324
  const INLINE_KNOWLEDGE_BASE_NAME = 'inline-knowledge';
10222
- /**
10223
- * @@@
10224
- *
10225
- * @private thing of inline knowledge
10226
- */
10325
+ /** @private The default file extension used for inline knowledge uploads */
10227
10326
  const INLINE_KNOWLEDGE_EXTENSION = '.txt';
10228
- /**
10229
- * @@@
10230
- *
10231
- * @private thing of inline knowledge
10232
- */
10327
+ /** @private Prefix that identifies base64 data URLs */
10233
10328
  const DATA_URL_PREFIX = 'data:';
10234
10329
  /**
10235
- * @@@
10236
- *
10237
- * @private thing of inline knowledge
10330
+ * @private Retrieves the first meaningful line from the inline content.
10238
10331
  */
10239
10332
  function getFirstNonEmptyLine(content) {
10240
10333
  const lines = content.split(/\r?\n/);
@@ -10247,9 +10340,7 @@ function getFirstNonEmptyLine(content) {
10247
10340
  return null;
10248
10341
  }
10249
10342
  /**
10250
- * @@@
10251
- *
10252
- * @private thing of inline knowledge
10343
+ * @private Determines the base file name by normalizing the first non-empty line.
10253
10344
  */
10254
10345
  function deriveBaseFilename(content) {
10255
10346
  const firstLine = getFirstNonEmptyLine(content);
@@ -10260,22 +10351,18 @@ function deriveBaseFilename(content) {
10260
10351
  return normalized || INLINE_KNOWLEDGE_BASE_NAME;
10261
10352
  }
10262
10353
  /**
10263
- * Creates a data URL that represents the inline knowledge content as a text file.
10264
- *
10265
- * @private thing of inline knowledge
10354
+ * @private Converts inline knowledge into the internal metadata form used for uploads.
10266
10355
  */
10267
10356
  function createInlineKnowledgeSourceFile(content) {
10268
10357
  const trimmedContent = content.trim();
10269
10358
  const baseName = deriveBaseFilename(trimmedContent);
10270
10359
  const filename = `${baseName}${INLINE_KNOWLEDGE_EXTENSION}`;
10271
10360
  const mimeType = 'text/plain';
10272
- const base64 = Buffer.from(trimmedContent, 'utf-8').toString('base64');
10273
- const encodedFilename = encodeURIComponent(filename);
10274
- const url = `${DATA_URL_PREFIX}${mimeType};name=${encodedFilename};charset=utf-8;base64,${base64}`;
10361
+ const buffer = Buffer.from(trimmedContent, 'utf-8');
10275
10362
  return {
10276
10363
  filename,
10277
10364
  mimeType,
10278
- url,
10365
+ buffer,
10279
10366
  };
10280
10367
  }
10281
10368
  /**
@@ -10286,10 +10373,18 @@ function createInlineKnowledgeSourceFile(content) {
10286
10373
  function isDataUrlKnowledgeSource(source) {
10287
10374
  return typeof source === 'string' && source.startsWith(DATA_URL_PREFIX);
10288
10375
  }
10376
+ /**
10377
+ * @private Converts a stored inline knowledge file into a data URL for backwards compatibility.
10378
+ */
10379
+ function inlineKnowledgeSourceToDataUrl(source) {
10380
+ const base64 = source.buffer.toString('base64');
10381
+ const encodedFilename = encodeURIComponent(source.filename);
10382
+ return `${DATA_URL_PREFIX}${source.mimeType};name=${encodedFilename};charset=utf-8;base64,${base64}`;
10383
+ }
10289
10384
  /**
10290
10385
  * Parses a data URL-based knowledge source into its raw buffer, filename, and MIME type.
10291
10386
  *
10292
- * @private thing of inline knowledge
10387
+ * @private utility of inline knowledge processing
10293
10388
  */
10294
10389
  function parseDataUrlKnowledgeSource(source) {
10295
10390
  if (!isDataUrlKnowledgeSource(source)) {
@@ -11331,10 +11426,10 @@ class OpenAiAssistantExecutionTools extends OpenAiVectorStoreHandler {
11331
11426
  const scriptTool = scriptTools[0]; // <- TODO: [🧠] Which script tool to use?
11332
11427
  functionResponse = await scriptTool.execute({
11333
11428
  scriptLanguage: 'javascript',
11334
- script: `
11335
- const args = ${JSON.stringify(functionArgs)};
11336
- return await ${functionName}(args);
11337
- `,
11429
+ script: buildToolInvocationScript({
11430
+ functionName,
11431
+ functionArgsExpression: JSON.stringify(functionArgs),
11432
+ }),
11338
11433
  parameters: prompt.parameters,
11339
11434
  });
11340
11435
  if (this.options.isVerbose) {
@@ -18464,6 +18559,7 @@ class KnowledgeCommitmentDefinition extends BaseCommitmentDefinition {
18464
18559
  `);
18465
18560
  }
18466
18561
  applyToAgentModelRequirements(requirements, content) {
18562
+ var _a;
18467
18563
  const trimmedContent = content.trim();
18468
18564
  if (!trimmedContent) {
18469
18565
  return requirements;
@@ -18484,9 +18580,13 @@ class KnowledgeCommitmentDefinition extends BaseCommitmentDefinition {
18484
18580
  }
18485
18581
  else {
18486
18582
  const inlineSource = createInlineKnowledgeSourceFile(trimmedContent);
18583
+ const existingInlineSources = (((_a = requirements._metadata) === null || _a === void 0 ? void 0 : _a.inlineKnowledgeSources) || []).slice();
18487
18584
  const updatedRequirements = {
18488
18585
  ...requirements,
18489
- knowledgeSources: [...(requirements.knowledgeSources || []), inlineSource.url],
18586
+ _metadata: {
18587
+ ...requirements._metadata,
18588
+ inlineKnowledgeSources: [...existingInlineSources, inlineSource],
18589
+ },
18490
18590
  };
18491
18591
  const knowledgeInfo = `Knowledge Source Inline: ${inlineSource.filename} (derived from inline content and processed for retrieval during chat)`;
18492
18592
  return this.appendToSystemMessage(updatedRequirements, knowledgeInfo, '\n\n');
@@ -18568,6 +18668,182 @@ class LanguageCommitmentDefinition extends BaseCommitmentDefinition {
18568
18668
  * Note: [💞] Ignore a discrepancy between file name and entity name
18569
18669
  */
18570
18670
 
18671
+ /**
18672
+ * @@@
18673
+ *
18674
+ * @private utility for commitments
18675
+ */
18676
+ function formatOptionalInstructionBlock(label, content) {
18677
+ const trimmedContent = spaceTrim$1(content);
18678
+ if (!trimmedContent) {
18679
+ return '';
18680
+ }
18681
+ return spaceTrim$1((block) => `
18682
+ - ${label}:
18683
+ ${block(trimmedContent
18684
+ .split(/\r?\n/)
18685
+ .map((line) => `- ${line}`)
18686
+ .join('\n'))}
18687
+ `);
18688
+ }
18689
+
18690
+ /**
18691
+ * Tool name used to retrieve persisted user memory.
18692
+ *
18693
+ * @private internal MEMORY commitment constant
18694
+ */
18695
+ const RETRIEVE_USER_MEMORY_TOOL_NAME = 'retrieve_user_memory';
18696
+ /**
18697
+ * Tool name used to store persisted user memory.
18698
+ *
18699
+ * @private internal MEMORY commitment constant
18700
+ */
18701
+ const STORE_USER_MEMORY_TOOL_NAME = 'store_user_memory';
18702
+ const UPDATE_USER_MEMORY_TOOL_NAME = 'update_user_memory';
18703
+ const DELETE_USER_MEMORY_TOOL_NAME = 'delete_user_memory';
18704
+ /**
18705
+ * Resolves runtime context from hidden tool arguments.
18706
+ *
18707
+ * @private utility of MEMORY commitment
18708
+ */
18709
+ function resolveMemoryRuntimeContext(args) {
18710
+ const runtimeContext = readToolRuntimeContextFromToolArgs(args);
18711
+ const memoryContext = runtimeContext === null || runtimeContext === void 0 ? void 0 : runtimeContext.memory;
18712
+ return {
18713
+ enabled: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.enabled) === true,
18714
+ userId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.userId,
18715
+ username: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.username,
18716
+ agentId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentId,
18717
+ agentName: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentName,
18718
+ isTeamConversation: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.isTeamConversation) === true,
18719
+ };
18720
+ }
18721
+ /**
18722
+ * Builds a disabled memory-tool response payload.
18723
+ *
18724
+ * @private utility of MEMORY commitment
18725
+ */
18726
+ function createDisabledMemoryResult(action, message) {
18727
+ if (action === 'retrieve') {
18728
+ return {
18729
+ action,
18730
+ status: 'disabled',
18731
+ memories: [],
18732
+ message,
18733
+ };
18734
+ }
18735
+ if (action === 'store') {
18736
+ return {
18737
+ action,
18738
+ status: 'disabled',
18739
+ message,
18740
+ };
18741
+ }
18742
+ if (action === 'update') {
18743
+ return {
18744
+ action,
18745
+ status: 'disabled',
18746
+ message,
18747
+ };
18748
+ }
18749
+ if (action === 'delete') {
18750
+ return {
18751
+ action,
18752
+ status: 'disabled',
18753
+ message,
18754
+ };
18755
+ }
18756
+ throw new Error(`Unsupported memory tool action: ${action}`);
18757
+ }
18758
+ /**
18759
+ * Gets the runtime adapter and returns a disabled result when unavailable.
18760
+ *
18761
+ * @private utility of MEMORY commitment
18762
+ */
18763
+ function getRuntimeAdapterOrDisabledResult(action, runtimeContext) {
18764
+ if (!runtimeContext.enabled || runtimeContext.isTeamConversation) {
18765
+ return {
18766
+ adapter: null,
18767
+ disabledResult: createDisabledMemoryResult(action, runtimeContext.isTeamConversation
18768
+ ? 'Memory is disabled for TEAM conversations.'
18769
+ : 'Memory is disabled for unauthenticated users.'),
18770
+ };
18771
+ }
18772
+ {
18773
+ return {
18774
+ adapter: null,
18775
+ disabledResult: createDisabledMemoryResult(action, 'Memory runtime is not available in this environment.'),
18776
+ };
18777
+ }
18778
+ }
18779
+ /**
18780
+ * Parses retrieve memory arguments.
18781
+ *
18782
+ * @private utility of MEMORY commitment
18783
+ */
18784
+ function parseRetrieveMemoryArgs(args) {
18785
+ const query = typeof args.query === 'string' ? args.query.trim() : undefined;
18786
+ const limit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.floor(args.limit) : undefined;
18787
+ return {
18788
+ query: query && query.length > 0 ? query : undefined,
18789
+ limit: limit && limit > 0 ? Math.min(limit, 20) : undefined,
18790
+ };
18791
+ }
18792
+ /**
18793
+ * Parses store memory arguments.
18794
+ *
18795
+ * @private utility of MEMORY commitment
18796
+ */
18797
+ function parseStoreMemoryArgs(args) {
18798
+ const content = typeof args.content === 'string' ? args.content.trim() : '';
18799
+ if (!content) {
18800
+ throw new Error('Memory content is required.');
18801
+ }
18802
+ return {
18803
+ content,
18804
+ isGlobal: args.isGlobal === true,
18805
+ };
18806
+ }
18807
+ /**
18808
+ * Parses a memory identifier argument shared across MEMORY tools.
18809
+ *
18810
+ * @private utility of MEMORY commitment
18811
+ */
18812
+ function parseMemoryIdArg(value) {
18813
+ const memoryId = typeof value === 'string' ? value.trim() : '';
18814
+ if (!memoryId) {
18815
+ throw new Error('Memory id is required.');
18816
+ }
18817
+ return memoryId;
18818
+ }
18819
+ /**
18820
+ * Parses update memory arguments.
18821
+ *
18822
+ * @private utility of MEMORY commitment
18823
+ */
18824
+ function parseUpdateMemoryArgs(args) {
18825
+ const memoryId = parseMemoryIdArg(args.memoryId);
18826
+ const content = typeof args.content === 'string' ? args.content.trim() : '';
18827
+ if (!content) {
18828
+ throw new Error('Memory content is required.');
18829
+ }
18830
+ const isGlobal = typeof args.isGlobal === 'boolean' ? args.isGlobal : undefined;
18831
+ return {
18832
+ memoryId,
18833
+ content,
18834
+ isGlobal,
18835
+ };
18836
+ }
18837
+ /**
18838
+ * Parses delete memory arguments.
18839
+ *
18840
+ * @private utility of MEMORY commitment
18841
+ */
18842
+ function parseDeleteMemoryArgs(args) {
18843
+ return {
18844
+ memoryId: parseMemoryIdArg(args.memoryId),
18845
+ };
18846
+ }
18571
18847
  /**
18572
18848
  * MEMORY commitment definition
18573
18849
  *
@@ -18589,6 +18865,9 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
18589
18865
  constructor(type = 'MEMORY') {
18590
18866
  super(type);
18591
18867
  }
18868
+ get requiresContent() {
18869
+ return false;
18870
+ }
18592
18871
  /**
18593
18872
  * Short one-line description of MEMORY.
18594
18873
  */
@@ -18608,21 +18887,14 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
18608
18887
  return spaceTrim$1(`
18609
18888
  # ${this.type}
18610
18889
 
18611
- Similar to KNOWLEDGE but focuses on remembering past interactions and user preferences. This commitment helps the agent maintain context about the user's history, preferences, and previous conversations.
18890
+ Enables persistent user memory for the current agent. The memory is stored by the runtime and can be retrieved in future conversations.
18612
18891
 
18613
18892
  ## Key aspects
18614
18893
 
18615
- - Both terms work identically and can be used interchangeably.
18616
- - Focuses on user-specific information and interaction history.
18617
- - Helps personalize responses based on past interactions.
18618
- - Maintains continuity across conversations.
18619
-
18620
- ## Differences from KNOWLEDGE
18621
-
18622
- - \`KNOWLEDGE\` is for domain expertise and factual information
18623
- - \`MEMORY\` is for user-specific context and preferences
18624
- - \`MEMORY\` creates more personalized interactions
18625
- - \`MEMORY\` often includes temporal or preference-based information
18894
+ - Both \`MEMORY\` and \`MEMORIES\` work identically.
18895
+ - Stores user-specific details through runtime tools.
18896
+ - Retrieves relevant memories for personalized responses.
18897
+ - Supports optional extra instructions in the commitment content.
18626
18898
 
18627
18899
  ## Examples
18628
18900
 
@@ -18630,10 +18902,7 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
18630
18902
  Personal Assistant
18631
18903
 
18632
18904
  PERSONA You are a personal productivity assistant
18633
- MEMORY User is a software developer working in JavaScript/React
18634
- MEMORY User prefers morning work sessions and afternoon meetings
18635
- MEMORY Previously helped with project planning for mobile apps
18636
- MEMORY User timezone: UTC-8 (Pacific Time)
18905
+ MEMORY Remember user projects and long-term preferences.
18637
18906
  GOAL Help optimize daily productivity and workflow
18638
18907
  \`\`\`
18639
18908
 
@@ -18641,10 +18910,7 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
18641
18910
  Learning Companion
18642
18911
 
18643
18912
  PERSONA You are an educational companion for programming students
18644
- MEMORY Student is learning Python as their first programming language
18645
- MEMORY Previous topics covered: variables, loops, functions
18646
- MEMORY Student learns best with practical examples and exercises
18647
- MEMORY Last session: working on list comprehensions
18913
+ MEMORY Remember only the student's learning progress and preferred study style.
18648
18914
  GOAL Provide progressive learning experiences tailored to student's pace
18649
18915
  \`\`\`
18650
18916
 
@@ -18652,23 +18918,245 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
18652
18918
  Customer Support Agent
18653
18919
 
18654
18920
  PERSONA You are a customer support representative
18655
- MEMORY Customer has premium subscription since 2023
18656
- MEMORY Previous issue: billing question resolved last month
18657
- MEMORY Customer prefers email communication over phone calls
18658
- MEMORY Account shows frequent use of advanced features
18921
+ MEMORY Remember only important support history and communication preferences.
18659
18922
  GOAL Provide personalized support based on customer history
18660
18923
  \`\`\`
18661
18924
  `);
18662
18925
  }
18663
18926
  applyToAgentModelRequirements(requirements, content) {
18664
- const trimmedContent = content.trim();
18665
- if (!trimmedContent) {
18666
- return requirements;
18927
+ const extraInstructions = formatOptionalInstructionBlock('Memory instructions', content);
18928
+ const existingTools = requirements.tools || [];
18929
+ const tools = [...existingTools];
18930
+ if (!tools.some((tool) => tool.name === RETRIEVE_USER_MEMORY_TOOL_NAME)) {
18931
+ tools.push({
18932
+ name: RETRIEVE_USER_MEMORY_TOOL_NAME,
18933
+ description: spaceTrim$1(`
18934
+ Retrieve previously stored user memories relevant to the current conversation.
18935
+ Use this before responding when user context can improve the answer.
18936
+ `),
18937
+ parameters: {
18938
+ type: 'object',
18939
+ properties: {
18940
+ query: {
18941
+ type: 'string',
18942
+ description: 'Optional query used to filter relevant memories.',
18943
+ },
18944
+ limit: {
18945
+ type: 'integer',
18946
+ description: 'Optional maximum number of memories to return (default 5, max 20).',
18947
+ },
18948
+ },
18949
+ },
18950
+ });
18951
+ }
18952
+ if (!tools.some((tool) => tool.name === STORE_USER_MEMORY_TOOL_NAME)) {
18953
+ tools.push({
18954
+ name: STORE_USER_MEMORY_TOOL_NAME,
18955
+ description: spaceTrim$1(`
18956
+ Store a durable user memory that should be remembered in future conversations.
18957
+ Store only stable and useful user-specific facts or preferences.
18958
+ `),
18959
+ parameters: {
18960
+ type: 'object',
18961
+ properties: {
18962
+ content: {
18963
+ type: 'string',
18964
+ description: 'Memory text to store.',
18965
+ },
18966
+ isGlobal: {
18967
+ type: 'boolean',
18968
+ description: 'Set true to make this memory global across all user agents.',
18969
+ },
18970
+ },
18971
+ required: ['content'],
18972
+ },
18973
+ });
18974
+ }
18975
+ if (!tools.some((tool) => tool.name === UPDATE_USER_MEMORY_TOOL_NAME)) {
18976
+ tools.push({
18977
+ name: UPDATE_USER_MEMORY_TOOL_NAME,
18978
+ description: spaceTrim$1(`
18979
+ Update an existing user memory after retrieving it, so the stored fact stays accurate.
18980
+ Always pass the memory id you retrieved along with the new content.
18981
+ `),
18982
+ parameters: {
18983
+ type: 'object',
18984
+ properties: {
18985
+ memoryId: {
18986
+ type: 'string',
18987
+ description: 'Unique identifier of the memory entry to update.',
18988
+ },
18989
+ content: {
18990
+ type: 'string',
18991
+ description: 'Updated memory text.',
18992
+ },
18993
+ isGlobal: {
18994
+ type: 'boolean',
18995
+ description: 'Set true to keep the fact global; omit or false to keep it agent-scoped.',
18996
+ },
18997
+ },
18998
+ required: ['memoryId', 'content'],
18999
+ },
19000
+ });
18667
19001
  }
18668
- // Create memory section for system message
18669
- const memorySection = `Memory: ${trimmedContent}`;
18670
- // Memory information is contextual and should be included in the system message
18671
- return this.appendToSystemMessage(requirements, memorySection, '\n\n');
19002
+ if (!tools.some((tool) => tool.name === DELETE_USER_MEMORY_TOOL_NAME)) {
19003
+ tools.push({
19004
+ name: DELETE_USER_MEMORY_TOOL_NAME,
19005
+ description: spaceTrim$1(`
19006
+ Delete a user memory that is no longer relevant. Deletions are soft so the record is hidden from future queries.
19007
+ `),
19008
+ parameters: {
19009
+ type: 'object',
19010
+ properties: {
19011
+ memoryId: {
19012
+ type: 'string',
19013
+ description: 'Unique identifier of the memory entry to delete.',
19014
+ },
19015
+ },
19016
+ required: ['memoryId'],
19017
+ },
19018
+ });
19019
+ }
19020
+ return this.appendToSystemMessage({
19021
+ ...requirements,
19022
+ tools,
19023
+ _metadata: {
19024
+ ...requirements._metadata,
19025
+ useMemory: content || true,
19026
+ },
19027
+ }, spaceTrim$1((block) => `
19028
+ Memory:
19029
+ - Prefer storing agent-scoped memories; only make them global when the fact should apply across all your agents.
19030
+ - You can use persistent user memory tools.
19031
+ - Use "${RETRIEVE_USER_MEMORY_TOOL_NAME}" to load relevant memory before answering.
19032
+ - Use "${STORE_USER_MEMORY_TOOL_NAME}" to save stable user-specific facts that improve future help.
19033
+ - Use "${UPDATE_USER_MEMORY_TOOL_NAME}" to refresh an existing memory when the content changes.
19034
+ - Use "${DELETE_USER_MEMORY_TOOL_NAME}" to delete memories that are no longer accurate (deletions are soft and hidden from future queries).
19035
+ - Store concise memory items and avoid duplicates.
19036
+ - Never claim memory was saved or loaded unless the tool confirms it.
19037
+ ${block(extraInstructions)}
19038
+ `));
19039
+ }
19040
+ /**
19041
+ * Gets human-readable titles for MEMORY tool functions.
19042
+ */
19043
+ getToolTitles() {
19044
+ return {
19045
+ [RETRIEVE_USER_MEMORY_TOOL_NAME]: 'User memory',
19046
+ [STORE_USER_MEMORY_TOOL_NAME]: 'Store user memory',
19047
+ [UPDATE_USER_MEMORY_TOOL_NAME]: 'Update user memory',
19048
+ [DELETE_USER_MEMORY_TOOL_NAME]: 'Delete user memory',
19049
+ };
19050
+ }
19051
+ /**
19052
+ * Gets MEMORY tool function implementations.
19053
+ */
19054
+ getToolFunctions() {
19055
+ return {
19056
+ async [RETRIEVE_USER_MEMORY_TOOL_NAME](args) {
19057
+ const runtimeContext = resolveMemoryRuntimeContext(args);
19058
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('retrieve', runtimeContext);
19059
+ if (!adapter || disabledResult) {
19060
+ return JSON.stringify(disabledResult);
19061
+ }
19062
+ const parsedArgs = parseRetrieveMemoryArgs(args);
19063
+ try {
19064
+ const memories = await adapter.retrieveMemories(parsedArgs, runtimeContext);
19065
+ const result = {
19066
+ action: 'retrieve',
19067
+ status: 'ok',
19068
+ query: parsedArgs.query,
19069
+ memories,
19070
+ };
19071
+ return JSON.stringify(result);
19072
+ }
19073
+ catch (error) {
19074
+ const result = {
19075
+ action: 'retrieve',
19076
+ status: 'error',
19077
+ query: parsedArgs.query,
19078
+ memories: [],
19079
+ message: error instanceof Error ? error.message : String(error),
19080
+ };
19081
+ return JSON.stringify(result);
19082
+ }
19083
+ },
19084
+ async [STORE_USER_MEMORY_TOOL_NAME](args) {
19085
+ const runtimeContext = resolveMemoryRuntimeContext(args);
19086
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('store', runtimeContext);
19087
+ if (!adapter || disabledResult) {
19088
+ return JSON.stringify(disabledResult);
19089
+ }
19090
+ try {
19091
+ const parsedArgs = parseStoreMemoryArgs(args);
19092
+ const memory = await adapter.storeMemory(parsedArgs, runtimeContext);
19093
+ const result = {
19094
+ action: 'store',
19095
+ status: 'stored',
19096
+ memory,
19097
+ };
19098
+ return JSON.stringify(result);
19099
+ }
19100
+ catch (error) {
19101
+ const result = {
19102
+ action: 'store',
19103
+ status: 'error',
19104
+ message: error instanceof Error ? error.message : String(error),
19105
+ };
19106
+ return JSON.stringify(result);
19107
+ }
19108
+ },
19109
+ async [UPDATE_USER_MEMORY_TOOL_NAME](args) {
19110
+ const runtimeContext = resolveMemoryRuntimeContext(args);
19111
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('update', runtimeContext);
19112
+ if (!adapter || disabledResult) {
19113
+ return JSON.stringify(disabledResult);
19114
+ }
19115
+ try {
19116
+ const parsedArgs = parseUpdateMemoryArgs(args);
19117
+ const memory = await adapter.updateMemory(parsedArgs, runtimeContext);
19118
+ const result = {
19119
+ action: 'update',
19120
+ status: 'updated',
19121
+ memory,
19122
+ };
19123
+ return JSON.stringify(result);
19124
+ }
19125
+ catch (error) {
19126
+ const result = {
19127
+ action: 'update',
19128
+ status: 'error',
19129
+ message: error instanceof Error ? error.message : String(error),
19130
+ };
19131
+ return JSON.stringify(result);
19132
+ }
19133
+ },
19134
+ async [DELETE_USER_MEMORY_TOOL_NAME](args) {
19135
+ const runtimeContext = resolveMemoryRuntimeContext(args);
19136
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('delete', runtimeContext);
19137
+ if (!adapter || disabledResult) {
19138
+ return JSON.stringify(disabledResult);
19139
+ }
19140
+ try {
19141
+ const parsedArgs = parseDeleteMemoryArgs(args);
19142
+ const deleted = await adapter.deleteMemory(parsedArgs, runtimeContext);
19143
+ const result = {
19144
+ action: 'delete',
19145
+ status: 'deleted',
19146
+ memoryId: deleted.id,
19147
+ };
19148
+ return JSON.stringify(result);
19149
+ }
19150
+ catch (error) {
19151
+ const result = {
19152
+ action: 'delete',
19153
+ status: 'error',
19154
+ message: error instanceof Error ? error.message : String(error),
19155
+ };
19156
+ return JSON.stringify(result);
19157
+ }
19158
+ },
19159
+ };
18672
19160
  }
18673
19161
  }
18674
19162
  /**
@@ -20781,14 +21269,30 @@ function buildTeammateRequest(message, context) {
20781
21269
  /**
20782
21270
  * Builds a minimal chat prompt for teammate calls.
20783
21271
  */
20784
- function buildTeammatePrompt(request) {
21272
+ function buildTeammatePrompt(request, runtimeContext) {
20785
21273
  return {
20786
21274
  title: 'Teammate consultation',
20787
21275
  modelRequirements: {
20788
21276
  modelVariant: 'CHAT',
20789
21277
  },
20790
21278
  content: request,
20791
- parameters: {},
21279
+ parameters: {
21280
+ [TOOL_RUNTIME_CONTEXT_PARAMETER]: serializeToolRuntimeContext(runtimeContext),
21281
+ },
21282
+ };
21283
+ }
21284
+ /**
21285
+ * Creates teammate runtime context and marks conversation as team-only memory-disabled.
21286
+ */
21287
+ function createTeamConversationRuntimeContext(value) {
21288
+ const runtimeContext = parseToolRuntimeContext(value) || {};
21289
+ return {
21290
+ ...runtimeContext,
21291
+ memory: {
21292
+ ...(runtimeContext.memory || {}),
21293
+ enabled: false,
21294
+ isTeamConversation: true,
21295
+ },
20792
21296
  };
20793
21297
  }
20794
21298
  /**
@@ -20832,7 +21336,7 @@ function createTeamToolFunction(entry) {
20832
21336
  let toolCalls;
20833
21337
  try {
20834
21338
  const remoteAgent = await getRemoteTeammateAgent(entry.teammate.url);
20835
- const prompt = buildTeammatePrompt(request);
21339
+ const prompt = buildTeammatePrompt(request, createTeamConversationRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]));
20836
21340
  const teammateResult = await remoteAgent.callChatModel(prompt);
20837
21341
  response = teammateResult.content || '';
20838
21342
  toolCalls =
@@ -21382,25 +21886,6 @@ class UseBrowserCommitmentDefinition extends BaseCommitmentDefinition {
21382
21886
  * Note: [💞] Ignore a discrepancy between file name and entity name
21383
21887
  */
21384
21888
 
21385
- /**
21386
- * @@@
21387
- *
21388
- * @private utility for commitments
21389
- */
21390
- function formatOptionalInstructionBlock(label, content) {
21391
- const trimmedContent = spaceTrim$1(content);
21392
- if (!trimmedContent) {
21393
- return '';
21394
- }
21395
- return spaceTrim$1((block) => `
21396
- - ${label}:
21397
- ${block(trimmedContent
21398
- .split(/\r?\n/)
21399
- .map((line) => `- ${line}`)
21400
- .join('\n'))}
21401
- `);
21402
- }
21403
-
21404
21889
  /**
21405
21890
  * Client-side safe wrapper for sending emails.
21406
21891
  *
@@ -21594,8 +22079,8 @@ class UseEmailCommitmentDefinition extends BaseCommitmentDefinition {
21594
22079
  /**
21595
22080
  * USE IMAGE GENERATOR commitment definition
21596
22081
  *
21597
- * The `USE IMAGE GENERATOR` commitment indicates that the agent should utilize an image generation tool
21598
- * to create images based on text prompts.
22082
+ * The `USE IMAGE GENERATOR` commitment indicates that the agent can output
22083
+ * markdown placeholders for UI-driven image generation.
21599
22084
  *
21600
22085
  * Example usage in agent source:
21601
22086
  *
@@ -21610,11 +22095,14 @@ class UseImageGeneratorCommitmentDefinition extends BaseCommitmentDefinition {
21610
22095
  constructor(type = 'USE IMAGE GENERATOR') {
21611
22096
  super(type, ['USE IMAGE GENERATION', 'IMAGE GENERATOR', 'IMAGE GENERATION', 'USE IMAGE']);
21612
22097
  }
22098
+ get requiresContent() {
22099
+ return false;
22100
+ }
21613
22101
  /**
21614
22102
  * Short one-line description of USE IMAGE GENERATOR.
21615
22103
  */
21616
22104
  get description() {
21617
- return 'Enable the agent to use an image generation tool for creating images from text prompts.';
22105
+ return 'Enable the agent to output markdown image placeholders that the UI turns into generated images.';
21618
22106
  }
21619
22107
  /**
21620
22108
  * Icon for this commitment.
@@ -21629,21 +22117,21 @@ class UseImageGeneratorCommitmentDefinition extends BaseCommitmentDefinition {
21629
22117
  return spaceTrim$1(`
21630
22118
  # USE IMAGE GENERATOR
21631
22119
 
21632
- Enables the agent to use an image generation tool to create images based on text prompts.
22120
+ Enables the agent to output markdown image placeholders that trigger image generation in the user interface.
21633
22121
 
21634
22122
  ## Key aspects
21635
22123
 
21636
22124
  - The content following \`USE IMAGE GENERATOR\` is an arbitrary text that the agent should know (e.g. style instructions or safety guidelines).
21637
- - The actual image generation is handled by the agent runtime using LLM execution tools.
21638
- - Allows the agent to generate visual content based on user requests.
21639
- - Returns the URL of the generated image.
22125
+ - The agent does **not** call an image-generation tool directly.
22126
+ - The agent inserts markdown notation: \`![alt](?image-prompt=...)\`.
22127
+ - The user interface detects the notation and generates the image asynchronously.
21640
22128
 
21641
22129
  ## Examples
21642
22130
 
21643
22131
  \`\`\`book
21644
22132
  Visual Artist
21645
22133
 
21646
- PERSONA You are a creative visual artist who can generate images.
22134
+ PERSONA You are a creative visual artist.
21647
22135
  USE IMAGE GENERATOR
21648
22136
  RULE Always describe the generated image to the user.
21649
22137
  \`\`\`
@@ -21653,80 +22141,28 @@ class UseImageGeneratorCommitmentDefinition extends BaseCommitmentDefinition {
21653
22141
 
21654
22142
  PERSONA You are an interior designer who helps users visualize their space.
21655
22143
  USE IMAGE GENERATOR Professional interior design renders.
21656
- ACTION Generate a preview of the designed room.
22144
+ ACTION Add one generated image placeholder whenever a user asks for a visual.
21657
22145
  \`\`\`
21658
22146
  `);
21659
22147
  }
21660
22148
  applyToAgentModelRequirements(requirements, content) {
21661
- // Get existing tools array or create new one
21662
- const existingTools = requirements.tools || [];
21663
- // Add 'generate_image' to tools if not already present
21664
- const updatedTools = existingTools.some((tool) => tool.name === 'generate_image')
21665
- ? existingTools
21666
- : [
21667
- ...existingTools,
21668
- {
21669
- name: 'generate_image',
21670
- description: spaceTrim$1(`
21671
- Generate an image from a text prompt.
21672
- Use this tool when the user asks to create, draw, or generate an image.
21673
- ${!content ? '' : `Style instructions / guidelines: ${content}`}
21674
- `),
21675
- parameters: {
21676
- type: 'object',
21677
- properties: {
21678
- prompt: {
21679
- type: 'string',
21680
- description: 'The detailed description of the image to generate',
21681
- },
21682
- },
21683
- required: ['prompt'],
21684
- },
21685
- },
21686
- ];
21687
- // Return requirements with updated tools and metadata
22149
+ const extraInstructions = formatOptionalInstructionBlock('Image instructions', content);
21688
22150
  return this.appendToSystemMessage({
21689
22151
  ...requirements,
21690
- tools: updatedTools,
21691
22152
  _metadata: {
21692
22153
  ...requirements._metadata,
21693
22154
  useImageGenerator: content || true,
21694
22155
  },
21695
- }, spaceTrim$1(`
21696
- You have access to an image generator. Use it to create images based on user requests.
21697
- When you generate an image, you will receive a URL of the generated image.
21698
- `));
21699
- }
21700
- /**
21701
- * Gets human-readable titles for tool functions provided by this commitment.
21702
- */
21703
- getToolTitles() {
21704
- return {
21705
- generate_image: 'Generate image',
21706
- };
21707
- }
21708
- /**
21709
- * Gets the `generate_image` tool function implementation.
21710
- */
21711
- getToolFunctions() {
21712
- return {
21713
- async generate_image(args, ...extra) {
21714
- console.log('!!!! [Tool] generate_image called', { args });
21715
- const { prompt } = args;
21716
- if (!prompt) {
21717
- throw new Error('Image prompt is required');
21718
- }
21719
- const { llmTools } = extra[0] || {};
21720
- if (!llmTools || !llmTools.callImageGenerationModel) {
21721
- throw new Error('Image generation is not supported by the current model provider');
21722
- }
21723
- const result = await llmTools.callImageGenerationModel({
21724
- content: prompt,
21725
- modelName: 'dall-e-3', // Defaulting to dall-e-3, but this could be configurable
21726
- });
21727
- return result.content;
21728
- },
21729
- };
22156
+ }, spaceTrim$1((block) => `
22157
+ Image generation:
22158
+ - You do not generate images directly and you do not call any image tool.
22159
+ - When the user asks for an image, include markdown notation in your message:
22160
+ \`![<alt text>](?image-prompt=<prompt>)\`
22161
+ - Keep \`<alt text>\` short and descriptive.
22162
+ - Keep \`<prompt>\` detailed so the generated image matches the request.
22163
+ - You can include normal explanatory text before and after the notation.
22164
+ ${block(extraInstructions)}
22165
+ `));
21730
22166
  }
21731
22167
  }
21732
22168
  /**
@@ -22927,6 +23363,7 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
22927
23363
  systemMessage: requirements.systemMessage + '\n\n' + exampleInteractionsContent,
22928
23364
  };
22929
23365
  }
23366
+ requirements = await applyPendingInlineKnowledgeSources(requirements, options === null || options === void 0 ? void 0 : options.inlineKnowledgeSourceUploader);
22930
23367
  // Remove comment lines (lines starting with #) from the final system message
22931
23368
  // while preserving the original content with comments in metadata
22932
23369
  const cleanedSystemMessage = removeCommentsFromSystemMessage(requirements.systemMessage);
@@ -22935,6 +23372,54 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
22935
23372
  systemMessage: cleanedSystemMessage,
22936
23373
  };
22937
23374
  }
23375
+ /**
23376
+ * @private Attempts to upload inline knowledge entries, falling back to legacy data URLs when the upload fails or is not configured.
23377
+ */
23378
+ async function applyPendingInlineKnowledgeSources(requirements, uploader) {
23379
+ var _a;
23380
+ const inlineSources = extractInlineKnowledgeSources(requirements._metadata);
23381
+ if (inlineSources.length === 0) {
23382
+ return requirements;
23383
+ }
23384
+ const knowledgeSources = [...((_a = requirements.knowledgeSources) !== null && _a !== void 0 ? _a : [])];
23385
+ for (const inlineSource of inlineSources) {
23386
+ const url = uploader
23387
+ ? await uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader)
23388
+ : inlineKnowledgeSourceToDataUrl(inlineSource);
23389
+ knowledgeSources.push(url);
23390
+ }
23391
+ return {
23392
+ ...requirements,
23393
+ knowledgeSources,
23394
+ _metadata: stripInlineKnowledgeMetadata(requirements._metadata),
23395
+ };
23396
+ }
23397
+ async function uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader) {
23398
+ try {
23399
+ return await uploader(inlineSource);
23400
+ }
23401
+ catch (error) {
23402
+ console.error('[inline-knowledge] Failed to upload inline source', {
23403
+ filename: inlineSource.filename,
23404
+ error,
23405
+ });
23406
+ return inlineKnowledgeSourceToDataUrl(inlineSource);
23407
+ }
23408
+ }
23409
+ function extractInlineKnowledgeSources(metadata) {
23410
+ if (!metadata) {
23411
+ return [];
23412
+ }
23413
+ const value = metadata.inlineKnowledgeSources;
23414
+ return Array.isArray(value) ? value : [];
23415
+ }
23416
+ function stripInlineKnowledgeMetadata(metadata) {
23417
+ if (!metadata || !Object.prototype.hasOwnProperty.call(metadata, 'inlineKnowledgeSources')) {
23418
+ return metadata;
23419
+ }
23420
+ const { inlineKnowledgeSources: _unusedInlineKnowledgeSources, ...rest } = metadata;
23421
+ return Object.keys(rest).length > 0 ? rest : undefined;
23422
+ }
22938
23423
  /**
22939
23424
  * Mocked security check for imported files
22940
23425
  *
@@ -30099,10 +30584,10 @@ class OpenAiAgentKitExecutionTools extends OpenAiVectorStoreHandler {
30099
30584
  try {
30100
30585
  return await scriptTool.execute({
30101
30586
  scriptLanguage: 'javascript',
30102
- script: `
30103
- const args = ${JSON.stringify(functionArgs)};
30104
- return await ${functionName}(args);
30105
- `,
30587
+ script: buildToolInvocationScript({
30588
+ functionName,
30589
+ functionArgsExpression: JSON.stringify(functionArgs),
30590
+ }),
30106
30591
  parameters: (_c = (_b = runContext === null || runContext === void 0 ? void 0 : runContext.context) === null || _b === void 0 ? void 0 : _b.parameters) !== null && _c !== void 0 ? _c : {},
30107
30592
  });
30108
30593
  }
@@ -31133,6 +31618,20 @@ async function _Agent_selfLearnTeacher(prompt, result) {
31133
31618
  * TODO: [🧠][😰]Agent is not working with the parameters, should it be?
31134
31619
  */
31135
31620
 
31621
+ /**
31622
+ * Keep-alive helpers used for streaming chat responses.
31623
+ *
31624
+ * These constants coordinate the signal sent by the Agents Server streaming
31625
+ * endpoint and the parser in the SDK so we can distinguish between
31626
+ * real content and occasional pings.
31627
+ *
31628
+ * @private internal streaming helper for Promptbook chat connections
31629
+ */
31630
+ const CHAT_STREAM_KEEP_ALIVE_TOKEN = 'STREAM_KEEP_ALIVE';
31631
+ /**
31632
+ * Note: [💞] Ignore a discrepancy between file name and entity name
31633
+ */
31634
+
31136
31635
  /**
31137
31636
  * Resolve a remote META IMAGE value into an absolute URL when possible.
31138
31637
  */
@@ -31207,7 +31706,9 @@ class RemoteAgent extends Agent {
31207
31706
  static async connect(options) {
31208
31707
  var _a, _b, _c;
31209
31708
  const agentProfileUrl = `${options.agentUrl}/api/profile`;
31210
- const profileResponse = await fetch(agentProfileUrl);
31709
+ const profileResponse = await fetch(agentProfileUrl, {
31710
+ headers: attachClientVersionHeader(),
31711
+ });
31211
31712
  // <- TODO: [🐱‍🚀] What about closed-source agents?
31212
31713
  // <- TODO: [🐱‍🚀] Maybe use promptbookFetch
31213
31714
  if (!profileResponse.ok) {
@@ -31308,6 +31809,7 @@ class RemoteAgent extends Agent {
31308
31809
  }
31309
31810
  const response = await fetch(`${this.agentUrl}/api/voice`, {
31310
31811
  method: 'POST',
31812
+ headers: attachClientVersionHeader(),
31311
31813
  body: formData,
31312
31814
  });
31313
31815
  if (!response.ok) {
@@ -31337,13 +31839,14 @@ class RemoteAgent extends Agent {
31337
31839
  const chatPrompt = prompt;
31338
31840
  const bookResponse = await fetch(`${this.agentUrl}/api/chat`, {
31339
31841
  method: 'POST',
31340
- headers: {
31842
+ headers: attachClientVersionHeader({
31341
31843
  'Content-Type': 'application/json',
31342
- },
31844
+ }),
31343
31845
  body: JSON.stringify({
31344
31846
  message: prompt.content,
31345
31847
  thread: chatPrompt.thread,
31346
31848
  attachments: chatPrompt.attachments,
31849
+ parameters: chatPrompt.parameters,
31347
31850
  }),
31348
31851
  });
31349
31852
  // <- TODO: [🐱‍🚀] What about closed-source agents?
@@ -31425,6 +31928,9 @@ class RemoteAgent extends Agent {
31425
31928
  const lines = textChunk.split(/\r?\n/);
31426
31929
  for (const line of lines) {
31427
31930
  const trimmedLine = line.trim();
31931
+ if (trimmedLine === CHAT_STREAM_KEEP_ALIVE_TOKEN) {
31932
+ continue;
31933
+ }
31428
31934
  let isToolCallLine = false;
31429
31935
  if (trimmedLine.startsWith('{') && trimmedLine.endsWith('}')) {
31430
31936
  try {