@promptbook/wizard 0.110.0-9 → 0.111.0-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.
Files changed (45) hide show
  1. package/esm/index.es.js +709 -109
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/src/_packages/components.index.d.ts +4 -0
  4. package/esm/typings/src/_packages/core.index.d.ts +2 -2
  5. package/esm/typings/src/_packages/types.index.d.ts +6 -0
  6. package/esm/typings/src/_packages/utils.index.d.ts +12 -0
  7. package/esm/typings/src/book-2.0/agent-source/AgentReferenceResolver.d.ts +18 -0
  8. package/esm/typings/src/book-2.0/agent-source/BookEditable.d.ts +41 -0
  9. package/esm/typings/src/book-2.0/agent-source/CreateAgentModelRequirementsOptions.d.ts +17 -0
  10. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirements.d.ts +8 -2
  11. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.agentReferenceResolver.test.d.ts +1 -0
  12. package/esm/typings/src/book-2.0/agent-source/createAgentModelRequirementsWithCommitments.d.ts +4 -5
  13. package/esm/typings/src/book-components/BookEditor/BookEditor.d.ts +42 -0
  14. package/esm/typings/src/book-components/Chat/Chat/ChatActionsBar.d.ts +0 -2
  15. package/esm/typings/src/book-components/Chat/Chat/ChatProps.d.ts +11 -0
  16. package/esm/typings/src/book-components/Chat/Chat/ChatSoundToggle.d.ts +12 -0
  17. package/esm/typings/src/book-components/Chat/Chat/ImagePromptRenderer.d.ts +21 -0
  18. package/esm/typings/src/book-components/Chat/LlmChat/LlmChatProps.d.ts +5 -0
  19. package/esm/typings/src/book-components/Chat/LlmChat/defaults.d.ts +9 -0
  20. package/esm/typings/src/book-components/Chat/hooks/useChatRatings.d.ts +24 -2
  21. package/esm/typings/src/book-components/Chat/save/_common/ChatSaveFormatDefinition.d.ts +7 -1
  22. package/esm/typings/src/book-components/Chat/save/html/htmlSaveFormatDefinition.d.ts +6 -5
  23. package/esm/typings/src/book-components/Chat/save/index.d.ts +3 -3
  24. package/esm/typings/src/book-components/Chat/save/pdf/buildChatPdf.d.ts +11 -0
  25. package/esm/typings/src/book-components/Chat/save/pdf/pdfSaveFormatDefinition.d.ts +2 -2
  26. package/esm/typings/src/book-components/Chat/utils/getToolCallChipletInfo.d.ts +2 -10
  27. package/esm/typings/src/book-components/Chat/utils/parseCitationMarker.d.ts +75 -0
  28. package/esm/typings/src/book-components/Chat/utils/parseCitationsFromContent.d.ts +3 -1
  29. package/esm/typings/src/book-components/Chat/utils/parseCitationsFromContent.test.d.ts +1 -0
  30. package/esm/typings/src/book-components/Chat/utils/parseImagePrompts.d.ts +42 -0
  31. package/esm/typings/src/book-components/Chat/utils/parseImagePrompts.test.d.ts +1 -0
  32. package/esm/typings/src/book-components/icons/ArrowIcon.d.ts +17 -4
  33. package/esm/typings/src/commitments/MEMORY/MEMORY.d.ts +67 -0
  34. package/esm/typings/src/commitments/MEMORY/MEMORY.test.d.ts +1 -0
  35. package/esm/typings/src/commitments/_common/toolRuntimeContext.d.ts +49 -0
  36. package/esm/typings/src/constants/streaming.d.ts +20 -0
  37. package/esm/typings/src/llm-providers/openai/utils/buildToolInvocationScript.d.ts +9 -0
  38. package/esm/typings/src/utils/clientVersion.d.ts +51 -0
  39. package/esm/typings/src/utils/knowledge/inlineKnowledgeSource.d.ts +13 -9
  40. package/esm/typings/src/utils/normalization/constructImageFilename.d.ts +18 -0
  41. package/esm/typings/src/utils/normalization/constructImageFilename.test.d.ts +1 -0
  42. package/esm/typings/src/version.d.ts +1 -1
  43. package/package.json +2 -2
  44. package/umd/index.umd.js +709 -109
  45. 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-9';
41
+ const PROMPTBOOK_ENGINE_VERSION = '0.111.0-0';
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
+ });
19001
+ }
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
+ });
18667
19019
  }
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');
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
  /**
@@ -20654,7 +21142,8 @@ class TeamCommitmentDefinition extends BaseCommitmentDefinition {
20654
21142
  if (!trimmedContent) {
20655
21143
  return requirements;
20656
21144
  }
20657
- const teammates = parseTeamCommitmentContent(trimmedContent, { strict: true });
21145
+ // Keep TEAM resilient: unresolved/malformed teammate entries are skipped, valid ones are still registered.
21146
+ const teammates = parseTeamCommitmentContent(trimmedContent, { strict: false });
20658
21147
  if (teammates.length === 0) {
20659
21148
  return requirements;
20660
21149
  }
@@ -20780,14 +21269,30 @@ function buildTeammateRequest(message, context) {
20780
21269
  /**
20781
21270
  * Builds a minimal chat prompt for teammate calls.
20782
21271
  */
20783
- function buildTeammatePrompt(request) {
21272
+ function buildTeammatePrompt(request, runtimeContext) {
20784
21273
  return {
20785
21274
  title: 'Teammate consultation',
20786
21275
  modelRequirements: {
20787
21276
  modelVariant: 'CHAT',
20788
21277
  },
20789
21278
  content: request,
20790
- 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
+ },
20791
21296
  };
20792
21297
  }
20793
21298
  /**
@@ -20831,7 +21336,7 @@ function createTeamToolFunction(entry) {
20831
21336
  let toolCalls;
20832
21337
  try {
20833
21338
  const remoteAgent = await getRemoteTeammateAgent(entry.teammate.url);
20834
- const prompt = buildTeammatePrompt(request);
21339
+ const prompt = buildTeammatePrompt(request, createTeamConversationRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]));
20835
21340
  const teammateResult = await remoteAgent.callChatModel(prompt);
20836
21341
  response = teammateResult.content || '';
20837
21342
  toolCalls =
@@ -21381,25 +21886,6 @@ class UseBrowserCommitmentDefinition extends BaseCommitmentDefinition {
21381
21886
  * Note: [💞] Ignore a discrepancy between file name and entity name
21382
21887
  */
21383
21888
 
21384
- /**
21385
- * @@@
21386
- *
21387
- * @private utility for commitments
21388
- */
21389
- function formatOptionalInstructionBlock(label, content) {
21390
- const trimmedContent = spaceTrim$1(content);
21391
- if (!trimmedContent) {
21392
- return '';
21393
- }
21394
- return spaceTrim$1((block) => `
21395
- - ${label}:
21396
- ${block(trimmedContent
21397
- .split(/\r?\n/)
21398
- .map((line) => `- ${line}`)
21399
- .join('\n'))}
21400
- `);
21401
- }
21402
-
21403
21889
  /**
21404
21890
  * Client-side safe wrapper for sending emails.
21405
21891
  *
@@ -22713,14 +23199,42 @@ function removeCommentsFromSystemMessage(systemMessage) {
22713
23199
  }
22714
23200
 
22715
23201
  /**
22716
- * Creates agent model requirements using the new commitment system
23202
+ * Creates agent model requirements using the new commitment system.
23203
+ *
22717
23204
  * This function uses a reduce-like pattern where each commitment applies its changes
22718
- * to build the final requirements starting from a basic empty model
23205
+ * to build the final requirements starting from a basic empty model.
22719
23206
  *
22720
- * @public exported from `@promptbook/core`
23207
+ * @param agentSource - Agent source book to parse.
23208
+ * @param modelName - Optional override for the agent model name.
23209
+ * @param options - Additional options such as the agent reference resolver.
23210
+ *
23211
+ * @private @@@
22721
23212
  */
22722
- async function createAgentModelRequirementsWithCommitments(agentSource, modelName) {
23213
+ const COMMITMENTS_WITH_AGENT_REFERENCES = new Set(['FROM', 'IMPORT', 'IMPORTS', 'TEAM']);
23214
+ /**
23215
+ * Returns a safe fallback content when a resolver fails to transform a reference commitment.
23216
+ *
23217
+ * @param commitmentType - Commitment being resolved.
23218
+ * @param originalContent - Original unresolved commitment content.
23219
+ * @returns Fallback content that keeps requirement creation resilient.
23220
+ */
23221
+ function getSafeReferenceCommitmentFallback(commitmentType, originalContent) {
23222
+ if (commitmentType === 'FROM') {
23223
+ return 'VOID';
23224
+ }
23225
+ if (commitmentType === 'IMPORT' || commitmentType === 'IMPORTS' || commitmentType === 'TEAM') {
23226
+ return '';
23227
+ }
23228
+ return originalContent;
23229
+ }
23230
+ /**
23231
+ * @@@
23232
+ *
23233
+ * @private @@@
23234
+ */
23235
+ async function createAgentModelRequirementsWithCommitments(agentSource, modelName, options) {
22723
23236
  var _a;
23237
+ const agentReferenceResolver = options === null || options === void 0 ? void 0 : options.agentReferenceResolver;
22724
23238
  // Parse the agent source to extract commitments
22725
23239
  const parseResult = parseAgentSourceWithCommitments(agentSource);
22726
23240
  // Apply DELETE filtering: remove prior commitments tagged by parameters targeted by DELETE/CANCEL/DISCARD/REMOVE
@@ -22772,6 +23286,17 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
22772
23286
  // Apply each commitment in order using reduce-like pattern
22773
23287
  for (let i = 0; i < filteredCommitments.length; i++) {
22774
23288
  const commitment = filteredCommitments[i];
23289
+ const isReferenceCommitment = Boolean(agentReferenceResolver && COMMITMENTS_WITH_AGENT_REFERENCES.has(commitment.type));
23290
+ let commitmentContent = commitment.content;
23291
+ if (isReferenceCommitment && agentReferenceResolver) {
23292
+ try {
23293
+ commitmentContent = await agentReferenceResolver.resolveCommitmentContent(commitment.type, commitment.content);
23294
+ }
23295
+ catch (error) {
23296
+ console.warn(`Failed to resolve commitment references for ${commitment.type}, falling back to safe defaults:`, error);
23297
+ commitmentContent = getSafeReferenceCommitmentFallback(commitment.type, commitment.content);
23298
+ }
23299
+ }
22775
23300
  // CLOSED commitment should work only if its the last commitment in the book
22776
23301
  if (commitment.type === 'CLOSED' && i !== filteredCommitments.length - 1) {
22777
23302
  continue;
@@ -22779,7 +23304,7 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
22779
23304
  const definition = getCommitmentDefinition(commitment.type);
22780
23305
  if (definition) {
22781
23306
  try {
22782
- requirements = definition.applyToAgentModelRequirements(requirements, commitment.content);
23307
+ requirements = definition.applyToAgentModelRequirements(requirements, commitmentContent);
22783
23308
  }
22784
23309
  catch (error) {
22785
23310
  console.warn(`Failed to apply commitment ${commitment.type}:`, error);
@@ -22887,6 +23412,7 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
22887
23412
  systemMessage: requirements.systemMessage + '\n\n' + exampleInteractionsContent,
22888
23413
  };
22889
23414
  }
23415
+ requirements = await applyPendingInlineKnowledgeSources(requirements, options === null || options === void 0 ? void 0 : options.inlineKnowledgeSourceUploader);
22890
23416
  // Remove comment lines (lines starting with #) from the final system message
22891
23417
  // while preserving the original content with comments in metadata
22892
23418
  const cleanedSystemMessage = removeCommentsFromSystemMessage(requirements.systemMessage);
@@ -22895,6 +23421,54 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
22895
23421
  systemMessage: cleanedSystemMessage,
22896
23422
  };
22897
23423
  }
23424
+ /**
23425
+ * @private Attempts to upload inline knowledge entries, falling back to legacy data URLs when the upload fails or is not configured.
23426
+ */
23427
+ async function applyPendingInlineKnowledgeSources(requirements, uploader) {
23428
+ var _a;
23429
+ const inlineSources = extractInlineKnowledgeSources(requirements._metadata);
23430
+ if (inlineSources.length === 0) {
23431
+ return requirements;
23432
+ }
23433
+ const knowledgeSources = [...((_a = requirements.knowledgeSources) !== null && _a !== void 0 ? _a : [])];
23434
+ for (const inlineSource of inlineSources) {
23435
+ const url = uploader
23436
+ ? await uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader)
23437
+ : inlineKnowledgeSourceToDataUrl(inlineSource);
23438
+ knowledgeSources.push(url);
23439
+ }
23440
+ return {
23441
+ ...requirements,
23442
+ knowledgeSources,
23443
+ _metadata: stripInlineKnowledgeMetadata(requirements._metadata),
23444
+ };
23445
+ }
23446
+ async function uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader) {
23447
+ try {
23448
+ return await uploader(inlineSource);
23449
+ }
23450
+ catch (error) {
23451
+ console.error('[inline-knowledge] Failed to upload inline source', {
23452
+ filename: inlineSource.filename,
23453
+ error,
23454
+ });
23455
+ return inlineKnowledgeSourceToDataUrl(inlineSource);
23456
+ }
23457
+ }
23458
+ function extractInlineKnowledgeSources(metadata) {
23459
+ if (!metadata) {
23460
+ return [];
23461
+ }
23462
+ const value = metadata.inlineKnowledgeSources;
23463
+ return Array.isArray(value) ? value : [];
23464
+ }
23465
+ function stripInlineKnowledgeMetadata(metadata) {
23466
+ if (!metadata || !Object.prototype.hasOwnProperty.call(metadata, 'inlineKnowledgeSources')) {
23467
+ return metadata;
23468
+ }
23469
+ const { inlineKnowledgeSources: _unusedInlineKnowledgeSources, ...rest } = metadata;
23470
+ return Object.keys(rest).length > 0 ? rest : undefined;
23471
+ }
22898
23472
  /**
22899
23473
  * Mocked security check for imported files
22900
23474
  *
@@ -23238,23 +23812,28 @@ function normalizeSeparator(content) {
23238
23812
  */
23239
23813
 
23240
23814
  /**
23241
- * Creates model requirements for an agent based on its source
23815
+ * Creates model requirements for an agent based on its source.
23242
23816
  *
23243
23817
  * There are 2 similar functions:
23244
23818
  * - `parseAgentSource` which is a lightweight parser for agent source, it parses basic information and its purpose is to be quick and synchronous. The commitments there are hardcoded.
23245
23819
  * - `createAgentModelRequirements` which is an asynchronous function that creates model requirements it applies each commitment one by one and works asynchronous.
23246
23820
  *
23821
+ * @param agentSource - Book describing the agent.
23822
+ * @param modelName - Optional override for the agent's model.
23823
+ * @param availableModels - Models that could fulfill the agent.
23824
+ * @param llmTools - Execution tools used when selecting a best model.
23825
+ * @param options - Optional hooks such as the agent reference resolver.
23247
23826
  * @public exported from `@promptbook/core`
23248
23827
  */
23249
- async function createAgentModelRequirements(agentSource, modelName, availableModels, llmTools) {
23828
+ async function createAgentModelRequirements(agentSource, modelName, availableModels, llmTools, options) {
23250
23829
  // If availableModels are provided and no specific modelName is given,
23251
23830
  // use preparePersona to select the best model
23252
23831
  if (availableModels && !modelName && llmTools) {
23253
23832
  const selectedModelName = await selectBestModelUsingPersona(agentSource, llmTools);
23254
- return createAgentModelRequirementsWithCommitments(agentSource, selectedModelName);
23833
+ return createAgentModelRequirementsWithCommitments(agentSource, selectedModelName, options);
23255
23834
  }
23256
23835
  // Use the new commitment-based system with provided or default model
23257
- return createAgentModelRequirementsWithCommitments(agentSource, modelName);
23836
+ return createAgentModelRequirementsWithCommitments(agentSource, modelName, options);
23258
23837
  }
23259
23838
  /**
23260
23839
  * Selects the best model using the preparePersona function
@@ -30054,10 +30633,10 @@ class OpenAiAgentKitExecutionTools extends OpenAiVectorStoreHandler {
30054
30633
  try {
30055
30634
  return await scriptTool.execute({
30056
30635
  scriptLanguage: 'javascript',
30057
- script: `
30058
- const args = ${JSON.stringify(functionArgs)};
30059
- return await ${functionName}(args);
30060
- `,
30636
+ script: buildToolInvocationScript({
30637
+ functionName,
30638
+ functionArgsExpression: JSON.stringify(functionArgs),
30639
+ }),
30061
30640
  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 : {},
30062
30641
  });
30063
30642
  }
@@ -31088,6 +31667,20 @@ async function _Agent_selfLearnTeacher(prompt, result) {
31088
31667
  * TODO: [🧠][😰]Agent is not working with the parameters, should it be?
31089
31668
  */
31090
31669
 
31670
+ /**
31671
+ * Keep-alive helpers used for streaming chat responses.
31672
+ *
31673
+ * These constants coordinate the signal sent by the Agents Server streaming
31674
+ * endpoint and the parser in the SDK so we can distinguish between
31675
+ * real content and occasional pings.
31676
+ *
31677
+ * @private internal streaming helper for Promptbook chat connections
31678
+ */
31679
+ const CHAT_STREAM_KEEP_ALIVE_TOKEN = 'STREAM_KEEP_ALIVE';
31680
+ /**
31681
+ * Note: [💞] Ignore a discrepancy between file name and entity name
31682
+ */
31683
+
31091
31684
  /**
31092
31685
  * Resolve a remote META IMAGE value into an absolute URL when possible.
31093
31686
  */
@@ -31162,7 +31755,9 @@ class RemoteAgent extends Agent {
31162
31755
  static async connect(options) {
31163
31756
  var _a, _b, _c;
31164
31757
  const agentProfileUrl = `${options.agentUrl}/api/profile`;
31165
- const profileResponse = await fetch(agentProfileUrl);
31758
+ const profileResponse = await fetch(agentProfileUrl, {
31759
+ headers: attachClientVersionHeader(),
31760
+ });
31166
31761
  // <- TODO: [🐱‍🚀] What about closed-source agents?
31167
31762
  // <- TODO: [🐱‍🚀] Maybe use promptbookFetch
31168
31763
  if (!profileResponse.ok) {
@@ -31263,6 +31858,7 @@ class RemoteAgent extends Agent {
31263
31858
  }
31264
31859
  const response = await fetch(`${this.agentUrl}/api/voice`, {
31265
31860
  method: 'POST',
31861
+ headers: attachClientVersionHeader(),
31266
31862
  body: formData,
31267
31863
  });
31268
31864
  if (!response.ok) {
@@ -31292,13 +31888,14 @@ class RemoteAgent extends Agent {
31292
31888
  const chatPrompt = prompt;
31293
31889
  const bookResponse = await fetch(`${this.agentUrl}/api/chat`, {
31294
31890
  method: 'POST',
31295
- headers: {
31891
+ headers: attachClientVersionHeader({
31296
31892
  'Content-Type': 'application/json',
31297
- },
31893
+ }),
31298
31894
  body: JSON.stringify({
31299
31895
  message: prompt.content,
31300
31896
  thread: chatPrompt.thread,
31301
31897
  attachments: chatPrompt.attachments,
31898
+ parameters: chatPrompt.parameters,
31302
31899
  }),
31303
31900
  });
31304
31901
  // <- TODO: [🐱‍🚀] What about closed-source agents?
@@ -31380,6 +31977,9 @@ class RemoteAgent extends Agent {
31380
31977
  const lines = textChunk.split(/\r?\n/);
31381
31978
  for (const line of lines) {
31382
31979
  const trimmedLine = line.trim();
31980
+ if (trimmedLine === CHAT_STREAM_KEEP_ALIVE_TOKEN) {
31981
+ continue;
31982
+ }
31383
31983
  let isToolCallLine = false;
31384
31984
  if (trimmedLine.startsWith('{') && trimmedLine.endsWith('}')) {
31385
31985
  try {