@promptbook/cli 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 +1 -1
  44. package/umd/index.umd.js +709 -109
  45. package/umd/index.umd.js.map +1 -1
package/esm/index.es.js CHANGED
@@ -48,7 +48,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
48
48
  * @generated
49
49
  * @see https://github.com/webgptorg/promptbook
50
50
  */
51
- const PROMPTBOOK_ENGINE_VERSION = '0.110.0-9';
51
+ const PROMPTBOOK_ENGINE_VERSION = '0.111.0-0';
52
52
  /**
53
53
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
54
54
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -4522,6 +4522,36 @@ function prompt(strings, ...values) {
4522
4522
  * Note: [💞] Ignore a discrepancy between file name and entity name
4523
4523
  */
4524
4524
 
4525
+ /**
4526
+ * HTTP header used by Promptbook clients to advertise their release version.
4527
+ *
4528
+ * @public exported from `@promptbook/utils`
4529
+ */
4530
+ const CLIENT_VERSION_HEADER = 'x-promptbook-client-version';
4531
+ /**
4532
+ * The latest client (engine) version that the server expects.
4533
+ *
4534
+ * @public exported from `@promptbook/utils`
4535
+ */
4536
+ const CLIENT_LATEST_VERSION = PROMPTBOOK_ENGINE_VERSION;
4537
+ /**
4538
+ * Creates a headers object that includes the client version header.
4539
+ *
4540
+ * @param headers - Optional base headers to clone.
4541
+ * @returns New headers object augmented with `CLIENT_VERSION_HEADER`.
4542
+ *
4543
+ * @public exported from `@promptbook/utils`
4544
+ */
4545
+ function attachClientVersionHeader(headers) {
4546
+ return {
4547
+ ...(headers !== null && headers !== void 0 ? headers : {}),
4548
+ [CLIENT_VERSION_HEADER]: CLIENT_LATEST_VERSION,
4549
+ };
4550
+ }
4551
+ /**
4552
+ * Note: [💞] Ignore a discrepancy between file name and entity name
4553
+ */
4554
+
4525
4555
  /**
4526
4556
  * Number of characters per standard line with 11pt Arial font size.
4527
4557
  *
@@ -16674,28 +16704,14 @@ class ImportCommitmentDefinition extends BaseCommitmentDefinition {
16674
16704
  * Note: [💞] Ignore a discrepancy between file name and entity name
16675
16705
  */
16676
16706
 
16677
- /**
16678
- * @@@
16679
- *
16680
- * @private thing of inline knowledge
16681
- */
16707
+ /** @private The default base name for inline knowledge files when the content lacks identifying text */
16682
16708
  const INLINE_KNOWLEDGE_BASE_NAME = 'inline-knowledge';
16683
- /**
16684
- * @@@
16685
- *
16686
- * @private thing of inline knowledge
16687
- */
16709
+ /** @private The default file extension used for inline knowledge uploads */
16688
16710
  const INLINE_KNOWLEDGE_EXTENSION = '.txt';
16689
- /**
16690
- * @@@
16691
- *
16692
- * @private thing of inline knowledge
16693
- */
16711
+ /** @private Prefix that identifies base64 data URLs */
16694
16712
  const DATA_URL_PREFIX = 'data:';
16695
16713
  /**
16696
- * @@@
16697
- *
16698
- * @private thing of inline knowledge
16714
+ * @private Retrieves the first meaningful line from the inline content.
16699
16715
  */
16700
16716
  function getFirstNonEmptyLine(content) {
16701
16717
  const lines = content.split(/\r?\n/);
@@ -16708,9 +16724,7 @@ function getFirstNonEmptyLine(content) {
16708
16724
  return null;
16709
16725
  }
16710
16726
  /**
16711
- * @@@
16712
- *
16713
- * @private thing of inline knowledge
16727
+ * @private Determines the base file name by normalizing the first non-empty line.
16714
16728
  */
16715
16729
  function deriveBaseFilename(content) {
16716
16730
  const firstLine = getFirstNonEmptyLine(content);
@@ -16721,22 +16735,18 @@ function deriveBaseFilename(content) {
16721
16735
  return normalized || INLINE_KNOWLEDGE_BASE_NAME;
16722
16736
  }
16723
16737
  /**
16724
- * Creates a data URL that represents the inline knowledge content as a text file.
16725
- *
16726
- * @private thing of inline knowledge
16738
+ * @private Converts inline knowledge into the internal metadata form used for uploads.
16727
16739
  */
16728
16740
  function createInlineKnowledgeSourceFile(content) {
16729
16741
  const trimmedContent = content.trim();
16730
16742
  const baseName = deriveBaseFilename(trimmedContent);
16731
16743
  const filename = `${baseName}${INLINE_KNOWLEDGE_EXTENSION}`;
16732
16744
  const mimeType = 'text/plain';
16733
- const base64 = Buffer.from(trimmedContent, 'utf-8').toString('base64');
16734
- const encodedFilename = encodeURIComponent(filename);
16735
- const url = `${DATA_URL_PREFIX}${mimeType};name=${encodedFilename};charset=utf-8;base64,${base64}`;
16745
+ const buffer = Buffer.from(trimmedContent, 'utf-8');
16736
16746
  return {
16737
16747
  filename,
16738
16748
  mimeType,
16739
- url,
16749
+ buffer,
16740
16750
  };
16741
16751
  }
16742
16752
  /**
@@ -16747,10 +16757,18 @@ function createInlineKnowledgeSourceFile(content) {
16747
16757
  function isDataUrlKnowledgeSource(source) {
16748
16758
  return typeof source === 'string' && source.startsWith(DATA_URL_PREFIX);
16749
16759
  }
16760
+ /**
16761
+ * @private Converts a stored inline knowledge file into a data URL for backwards compatibility.
16762
+ */
16763
+ function inlineKnowledgeSourceToDataUrl(source) {
16764
+ const base64 = source.buffer.toString('base64');
16765
+ const encodedFilename = encodeURIComponent(source.filename);
16766
+ return `${DATA_URL_PREFIX}${source.mimeType};name=${encodedFilename};charset=utf-8;base64,${base64}`;
16767
+ }
16750
16768
  /**
16751
16769
  * Parses a data URL-based knowledge source into its raw buffer, filename, and MIME type.
16752
16770
  *
16753
- * @private thing of inline knowledge
16771
+ * @private utility of inline knowledge processing
16754
16772
  */
16755
16773
  function parseDataUrlKnowledgeSource(source) {
16756
16774
  if (!isDataUrlKnowledgeSource(source)) {
@@ -16883,6 +16901,7 @@ class KnowledgeCommitmentDefinition extends BaseCommitmentDefinition {
16883
16901
  `);
16884
16902
  }
16885
16903
  applyToAgentModelRequirements(requirements, content) {
16904
+ var _a;
16886
16905
  const trimmedContent = content.trim();
16887
16906
  if (!trimmedContent) {
16888
16907
  return requirements;
@@ -16903,9 +16922,13 @@ class KnowledgeCommitmentDefinition extends BaseCommitmentDefinition {
16903
16922
  }
16904
16923
  else {
16905
16924
  const inlineSource = createInlineKnowledgeSourceFile(trimmedContent);
16925
+ const existingInlineSources = (((_a = requirements._metadata) === null || _a === void 0 ? void 0 : _a.inlineKnowledgeSources) || []).slice();
16906
16926
  const updatedRequirements = {
16907
16927
  ...requirements,
16908
- knowledgeSources: [...(requirements.knowledgeSources || []), inlineSource.url],
16928
+ _metadata: {
16929
+ ...requirements._metadata,
16930
+ inlineKnowledgeSources: [...existingInlineSources, inlineSource],
16931
+ },
16909
16932
  };
16910
16933
  const knowledgeInfo = `Knowledge Source Inline: ${inlineSource.filename} (derived from inline content and processed for retrieval during chat)`;
16911
16934
  return this.appendToSystemMessage(updatedRequirements, knowledgeInfo, '\n\n');
@@ -16987,6 +17010,237 @@ class LanguageCommitmentDefinition extends BaseCommitmentDefinition {
16987
17010
  * Note: [💞] Ignore a discrepancy between file name and entity name
16988
17011
  */
16989
17012
 
17013
+ /**
17014
+ * @@@
17015
+ *
17016
+ * @private utility for commitments
17017
+ */
17018
+ function formatOptionalInstructionBlock(label, content) {
17019
+ const trimmedContent = spaceTrim$1(content);
17020
+ if (!trimmedContent) {
17021
+ return '';
17022
+ }
17023
+ return spaceTrim$1((block) => `
17024
+ - ${label}:
17025
+ ${block(trimmedContent
17026
+ .split(/\r?\n/)
17027
+ .map((line) => `- ${line}`)
17028
+ .join('\n'))}
17029
+ `);
17030
+ }
17031
+
17032
+ /**
17033
+ * Prompt parameter key used to pass hidden runtime context to tool execution.
17034
+ *
17035
+ * @private internal runtime wiring for commitment tools
17036
+ */
17037
+ const TOOL_RUNTIME_CONTEXT_PARAMETER = 'promptbookToolRuntimeContext';
17038
+ /**
17039
+ * Hidden argument key used to pass runtime context into individual tool calls.
17040
+ *
17041
+ * @private internal runtime wiring for commitment tools
17042
+ */
17043
+ const TOOL_RUNTIME_CONTEXT_ARGUMENT = '__promptbookToolRuntimeContext';
17044
+ /**
17045
+ * Parses unknown runtime context payload into a normalized object.
17046
+ *
17047
+ * @private internal runtime wiring for commitment tools
17048
+ */
17049
+ function parseToolRuntimeContext(rawValue) {
17050
+ if (!rawValue) {
17051
+ return null;
17052
+ }
17053
+ let parsed = rawValue;
17054
+ if (typeof rawValue === 'string') {
17055
+ try {
17056
+ parsed = JSON.parse(rawValue);
17057
+ }
17058
+ catch (_a) {
17059
+ return null;
17060
+ }
17061
+ }
17062
+ if (!parsed || typeof parsed !== 'object') {
17063
+ return null;
17064
+ }
17065
+ return parsed;
17066
+ }
17067
+ /**
17068
+ * Reads runtime context attached to tool call arguments.
17069
+ *
17070
+ * @private internal runtime wiring for commitment tools
17071
+ */
17072
+ function readToolRuntimeContextFromToolArgs(args) {
17073
+ return parseToolRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]);
17074
+ }
17075
+ /**
17076
+ * Serializes runtime context for prompt parameters.
17077
+ *
17078
+ * @private internal runtime wiring for commitment tools
17079
+ */
17080
+ function serializeToolRuntimeContext(context) {
17081
+ return JSON.stringify(context);
17082
+ }
17083
+ /**
17084
+ * Note: [💞] Ignore a discrepancy between file name and entity name
17085
+ */
17086
+
17087
+ /**
17088
+ * Tool name used to retrieve persisted user memory.
17089
+ *
17090
+ * @private internal MEMORY commitment constant
17091
+ */
17092
+ const RETRIEVE_USER_MEMORY_TOOL_NAME = 'retrieve_user_memory';
17093
+ /**
17094
+ * Tool name used to store persisted user memory.
17095
+ *
17096
+ * @private internal MEMORY commitment constant
17097
+ */
17098
+ const STORE_USER_MEMORY_TOOL_NAME = 'store_user_memory';
17099
+ const UPDATE_USER_MEMORY_TOOL_NAME = 'update_user_memory';
17100
+ const DELETE_USER_MEMORY_TOOL_NAME = 'delete_user_memory';
17101
+ /**
17102
+ * Resolves runtime context from hidden tool arguments.
17103
+ *
17104
+ * @private utility of MEMORY commitment
17105
+ */
17106
+ function resolveMemoryRuntimeContext(args) {
17107
+ const runtimeContext = readToolRuntimeContextFromToolArgs(args);
17108
+ const memoryContext = runtimeContext === null || runtimeContext === void 0 ? void 0 : runtimeContext.memory;
17109
+ return {
17110
+ enabled: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.enabled) === true,
17111
+ userId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.userId,
17112
+ username: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.username,
17113
+ agentId: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentId,
17114
+ agentName: memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.agentName,
17115
+ isTeamConversation: (memoryContext === null || memoryContext === void 0 ? void 0 : memoryContext.isTeamConversation) === true,
17116
+ };
17117
+ }
17118
+ /**
17119
+ * Builds a disabled memory-tool response payload.
17120
+ *
17121
+ * @private utility of MEMORY commitment
17122
+ */
17123
+ function createDisabledMemoryResult(action, message) {
17124
+ if (action === 'retrieve') {
17125
+ return {
17126
+ action,
17127
+ status: 'disabled',
17128
+ memories: [],
17129
+ message,
17130
+ };
17131
+ }
17132
+ if (action === 'store') {
17133
+ return {
17134
+ action,
17135
+ status: 'disabled',
17136
+ message,
17137
+ };
17138
+ }
17139
+ if (action === 'update') {
17140
+ return {
17141
+ action,
17142
+ status: 'disabled',
17143
+ message,
17144
+ };
17145
+ }
17146
+ if (action === 'delete') {
17147
+ return {
17148
+ action,
17149
+ status: 'disabled',
17150
+ message,
17151
+ };
17152
+ }
17153
+ throw new Error(`Unsupported memory tool action: ${action}`);
17154
+ }
17155
+ /**
17156
+ * Gets the runtime adapter and returns a disabled result when unavailable.
17157
+ *
17158
+ * @private utility of MEMORY commitment
17159
+ */
17160
+ function getRuntimeAdapterOrDisabledResult(action, runtimeContext) {
17161
+ if (!runtimeContext.enabled || runtimeContext.isTeamConversation) {
17162
+ return {
17163
+ adapter: null,
17164
+ disabledResult: createDisabledMemoryResult(action, runtimeContext.isTeamConversation
17165
+ ? 'Memory is disabled for TEAM conversations.'
17166
+ : 'Memory is disabled for unauthenticated users.'),
17167
+ };
17168
+ }
17169
+ {
17170
+ return {
17171
+ adapter: null,
17172
+ disabledResult: createDisabledMemoryResult(action, 'Memory runtime is not available in this environment.'),
17173
+ };
17174
+ }
17175
+ }
17176
+ /**
17177
+ * Parses retrieve memory arguments.
17178
+ *
17179
+ * @private utility of MEMORY commitment
17180
+ */
17181
+ function parseRetrieveMemoryArgs(args) {
17182
+ const query = typeof args.query === 'string' ? args.query.trim() : undefined;
17183
+ const limit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.floor(args.limit) : undefined;
17184
+ return {
17185
+ query: query && query.length > 0 ? query : undefined,
17186
+ limit: limit && limit > 0 ? Math.min(limit, 20) : undefined,
17187
+ };
17188
+ }
17189
+ /**
17190
+ * Parses store memory arguments.
17191
+ *
17192
+ * @private utility of MEMORY commitment
17193
+ */
17194
+ function parseStoreMemoryArgs(args) {
17195
+ const content = typeof args.content === 'string' ? args.content.trim() : '';
17196
+ if (!content) {
17197
+ throw new Error('Memory content is required.');
17198
+ }
17199
+ return {
17200
+ content,
17201
+ isGlobal: args.isGlobal === true,
17202
+ };
17203
+ }
17204
+ /**
17205
+ * Parses a memory identifier argument shared across MEMORY tools.
17206
+ *
17207
+ * @private utility of MEMORY commitment
17208
+ */
17209
+ function parseMemoryIdArg(value) {
17210
+ const memoryId = typeof value === 'string' ? value.trim() : '';
17211
+ if (!memoryId) {
17212
+ throw new Error('Memory id is required.');
17213
+ }
17214
+ return memoryId;
17215
+ }
17216
+ /**
17217
+ * Parses update memory arguments.
17218
+ *
17219
+ * @private utility of MEMORY commitment
17220
+ */
17221
+ function parseUpdateMemoryArgs(args) {
17222
+ const memoryId = parseMemoryIdArg(args.memoryId);
17223
+ const content = typeof args.content === 'string' ? args.content.trim() : '';
17224
+ if (!content) {
17225
+ throw new Error('Memory content is required.');
17226
+ }
17227
+ const isGlobal = typeof args.isGlobal === 'boolean' ? args.isGlobal : undefined;
17228
+ return {
17229
+ memoryId,
17230
+ content,
17231
+ isGlobal,
17232
+ };
17233
+ }
17234
+ /**
17235
+ * Parses delete memory arguments.
17236
+ *
17237
+ * @private utility of MEMORY commitment
17238
+ */
17239
+ function parseDeleteMemoryArgs(args) {
17240
+ return {
17241
+ memoryId: parseMemoryIdArg(args.memoryId),
17242
+ };
17243
+ }
16990
17244
  /**
16991
17245
  * MEMORY commitment definition
16992
17246
  *
@@ -17008,6 +17262,9 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
17008
17262
  constructor(type = 'MEMORY') {
17009
17263
  super(type);
17010
17264
  }
17265
+ get requiresContent() {
17266
+ return false;
17267
+ }
17011
17268
  /**
17012
17269
  * Short one-line description of MEMORY.
17013
17270
  */
@@ -17027,21 +17284,14 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
17027
17284
  return spaceTrim$1(`
17028
17285
  # ${this.type}
17029
17286
 
17030
- 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.
17287
+ Enables persistent user memory for the current agent. The memory is stored by the runtime and can be retrieved in future conversations.
17031
17288
 
17032
17289
  ## Key aspects
17033
17290
 
17034
- - Both terms work identically and can be used interchangeably.
17035
- - Focuses on user-specific information and interaction history.
17036
- - Helps personalize responses based on past interactions.
17037
- - Maintains continuity across conversations.
17038
-
17039
- ## Differences from KNOWLEDGE
17040
-
17041
- - \`KNOWLEDGE\` is for domain expertise and factual information
17042
- - \`MEMORY\` is for user-specific context and preferences
17043
- - \`MEMORY\` creates more personalized interactions
17044
- - \`MEMORY\` often includes temporal or preference-based information
17291
+ - Both \`MEMORY\` and \`MEMORIES\` work identically.
17292
+ - Stores user-specific details through runtime tools.
17293
+ - Retrieves relevant memories for personalized responses.
17294
+ - Supports optional extra instructions in the commitment content.
17045
17295
 
17046
17296
  ## Examples
17047
17297
 
@@ -17049,10 +17299,7 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
17049
17299
  Personal Assistant
17050
17300
 
17051
17301
  PERSONA You are a personal productivity assistant
17052
- MEMORY User is a software developer working in JavaScript/React
17053
- MEMORY User prefers morning work sessions and afternoon meetings
17054
- MEMORY Previously helped with project planning for mobile apps
17055
- MEMORY User timezone: UTC-8 (Pacific Time)
17302
+ MEMORY Remember user projects and long-term preferences.
17056
17303
  GOAL Help optimize daily productivity and workflow
17057
17304
  \`\`\`
17058
17305
 
@@ -17060,10 +17307,7 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
17060
17307
  Learning Companion
17061
17308
 
17062
17309
  PERSONA You are an educational companion for programming students
17063
- MEMORY Student is learning Python as their first programming language
17064
- MEMORY Previous topics covered: variables, loops, functions
17065
- MEMORY Student learns best with practical examples and exercises
17066
- MEMORY Last session: working on list comprehensions
17310
+ MEMORY Remember only the student's learning progress and preferred study style.
17067
17311
  GOAL Provide progressive learning experiences tailored to student's pace
17068
17312
  \`\`\`
17069
17313
 
@@ -17071,23 +17315,245 @@ class MemoryCommitmentDefinition extends BaseCommitmentDefinition {
17071
17315
  Customer Support Agent
17072
17316
 
17073
17317
  PERSONA You are a customer support representative
17074
- MEMORY Customer has premium subscription since 2023
17075
- MEMORY Previous issue: billing question resolved last month
17076
- MEMORY Customer prefers email communication over phone calls
17077
- MEMORY Account shows frequent use of advanced features
17318
+ MEMORY Remember only important support history and communication preferences.
17078
17319
  GOAL Provide personalized support based on customer history
17079
17320
  \`\`\`
17080
17321
  `);
17081
17322
  }
17082
17323
  applyToAgentModelRequirements(requirements, content) {
17083
- const trimmedContent = content.trim();
17084
- if (!trimmedContent) {
17085
- return requirements;
17324
+ const extraInstructions = formatOptionalInstructionBlock('Memory instructions', content);
17325
+ const existingTools = requirements.tools || [];
17326
+ const tools = [...existingTools];
17327
+ if (!tools.some((tool) => tool.name === RETRIEVE_USER_MEMORY_TOOL_NAME)) {
17328
+ tools.push({
17329
+ name: RETRIEVE_USER_MEMORY_TOOL_NAME,
17330
+ description: spaceTrim$1(`
17331
+ Retrieve previously stored user memories relevant to the current conversation.
17332
+ Use this before responding when user context can improve the answer.
17333
+ `),
17334
+ parameters: {
17335
+ type: 'object',
17336
+ properties: {
17337
+ query: {
17338
+ type: 'string',
17339
+ description: 'Optional query used to filter relevant memories.',
17340
+ },
17341
+ limit: {
17342
+ type: 'integer',
17343
+ description: 'Optional maximum number of memories to return (default 5, max 20).',
17344
+ },
17345
+ },
17346
+ },
17347
+ });
17348
+ }
17349
+ if (!tools.some((tool) => tool.name === STORE_USER_MEMORY_TOOL_NAME)) {
17350
+ tools.push({
17351
+ name: STORE_USER_MEMORY_TOOL_NAME,
17352
+ description: spaceTrim$1(`
17353
+ Store a durable user memory that should be remembered in future conversations.
17354
+ Store only stable and useful user-specific facts or preferences.
17355
+ `),
17356
+ parameters: {
17357
+ type: 'object',
17358
+ properties: {
17359
+ content: {
17360
+ type: 'string',
17361
+ description: 'Memory text to store.',
17362
+ },
17363
+ isGlobal: {
17364
+ type: 'boolean',
17365
+ description: 'Set true to make this memory global across all user agents.',
17366
+ },
17367
+ },
17368
+ required: ['content'],
17369
+ },
17370
+ });
17086
17371
  }
17087
- // Create memory section for system message
17088
- const memorySection = `Memory: ${trimmedContent}`;
17089
- // Memory information is contextual and should be included in the system message
17090
- return this.appendToSystemMessage(requirements, memorySection, '\n\n');
17372
+ if (!tools.some((tool) => tool.name === UPDATE_USER_MEMORY_TOOL_NAME)) {
17373
+ tools.push({
17374
+ name: UPDATE_USER_MEMORY_TOOL_NAME,
17375
+ description: spaceTrim$1(`
17376
+ Update an existing user memory after retrieving it, so the stored fact stays accurate.
17377
+ Always pass the memory id you retrieved along with the new content.
17378
+ `),
17379
+ parameters: {
17380
+ type: 'object',
17381
+ properties: {
17382
+ memoryId: {
17383
+ type: 'string',
17384
+ description: 'Unique identifier of the memory entry to update.',
17385
+ },
17386
+ content: {
17387
+ type: 'string',
17388
+ description: 'Updated memory text.',
17389
+ },
17390
+ isGlobal: {
17391
+ type: 'boolean',
17392
+ description: 'Set true to keep the fact global; omit or false to keep it agent-scoped.',
17393
+ },
17394
+ },
17395
+ required: ['memoryId', 'content'],
17396
+ },
17397
+ });
17398
+ }
17399
+ if (!tools.some((tool) => tool.name === DELETE_USER_MEMORY_TOOL_NAME)) {
17400
+ tools.push({
17401
+ name: DELETE_USER_MEMORY_TOOL_NAME,
17402
+ description: spaceTrim$1(`
17403
+ Delete a user memory that is no longer relevant. Deletions are soft so the record is hidden from future queries.
17404
+ `),
17405
+ parameters: {
17406
+ type: 'object',
17407
+ properties: {
17408
+ memoryId: {
17409
+ type: 'string',
17410
+ description: 'Unique identifier of the memory entry to delete.',
17411
+ },
17412
+ },
17413
+ required: ['memoryId'],
17414
+ },
17415
+ });
17416
+ }
17417
+ return this.appendToSystemMessage({
17418
+ ...requirements,
17419
+ tools,
17420
+ _metadata: {
17421
+ ...requirements._metadata,
17422
+ useMemory: content || true,
17423
+ },
17424
+ }, spaceTrim$1((block) => `
17425
+ Memory:
17426
+ - Prefer storing agent-scoped memories; only make them global when the fact should apply across all your agents.
17427
+ - You can use persistent user memory tools.
17428
+ - Use "${RETRIEVE_USER_MEMORY_TOOL_NAME}" to load relevant memory before answering.
17429
+ - Use "${STORE_USER_MEMORY_TOOL_NAME}" to save stable user-specific facts that improve future help.
17430
+ - Use "${UPDATE_USER_MEMORY_TOOL_NAME}" to refresh an existing memory when the content changes.
17431
+ - Use "${DELETE_USER_MEMORY_TOOL_NAME}" to delete memories that are no longer accurate (deletions are soft and hidden from future queries).
17432
+ - Store concise memory items and avoid duplicates.
17433
+ - Never claim memory was saved or loaded unless the tool confirms it.
17434
+ ${block(extraInstructions)}
17435
+ `));
17436
+ }
17437
+ /**
17438
+ * Gets human-readable titles for MEMORY tool functions.
17439
+ */
17440
+ getToolTitles() {
17441
+ return {
17442
+ [RETRIEVE_USER_MEMORY_TOOL_NAME]: 'User memory',
17443
+ [STORE_USER_MEMORY_TOOL_NAME]: 'Store user memory',
17444
+ [UPDATE_USER_MEMORY_TOOL_NAME]: 'Update user memory',
17445
+ [DELETE_USER_MEMORY_TOOL_NAME]: 'Delete user memory',
17446
+ };
17447
+ }
17448
+ /**
17449
+ * Gets MEMORY tool function implementations.
17450
+ */
17451
+ getToolFunctions() {
17452
+ return {
17453
+ async [RETRIEVE_USER_MEMORY_TOOL_NAME](args) {
17454
+ const runtimeContext = resolveMemoryRuntimeContext(args);
17455
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('retrieve', runtimeContext);
17456
+ if (!adapter || disabledResult) {
17457
+ return JSON.stringify(disabledResult);
17458
+ }
17459
+ const parsedArgs = parseRetrieveMemoryArgs(args);
17460
+ try {
17461
+ const memories = await adapter.retrieveMemories(parsedArgs, runtimeContext);
17462
+ const result = {
17463
+ action: 'retrieve',
17464
+ status: 'ok',
17465
+ query: parsedArgs.query,
17466
+ memories,
17467
+ };
17468
+ return JSON.stringify(result);
17469
+ }
17470
+ catch (error) {
17471
+ const result = {
17472
+ action: 'retrieve',
17473
+ status: 'error',
17474
+ query: parsedArgs.query,
17475
+ memories: [],
17476
+ message: error instanceof Error ? error.message : String(error),
17477
+ };
17478
+ return JSON.stringify(result);
17479
+ }
17480
+ },
17481
+ async [STORE_USER_MEMORY_TOOL_NAME](args) {
17482
+ const runtimeContext = resolveMemoryRuntimeContext(args);
17483
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('store', runtimeContext);
17484
+ if (!adapter || disabledResult) {
17485
+ return JSON.stringify(disabledResult);
17486
+ }
17487
+ try {
17488
+ const parsedArgs = parseStoreMemoryArgs(args);
17489
+ const memory = await adapter.storeMemory(parsedArgs, runtimeContext);
17490
+ const result = {
17491
+ action: 'store',
17492
+ status: 'stored',
17493
+ memory,
17494
+ };
17495
+ return JSON.stringify(result);
17496
+ }
17497
+ catch (error) {
17498
+ const result = {
17499
+ action: 'store',
17500
+ status: 'error',
17501
+ message: error instanceof Error ? error.message : String(error),
17502
+ };
17503
+ return JSON.stringify(result);
17504
+ }
17505
+ },
17506
+ async [UPDATE_USER_MEMORY_TOOL_NAME](args) {
17507
+ const runtimeContext = resolveMemoryRuntimeContext(args);
17508
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('update', runtimeContext);
17509
+ if (!adapter || disabledResult) {
17510
+ return JSON.stringify(disabledResult);
17511
+ }
17512
+ try {
17513
+ const parsedArgs = parseUpdateMemoryArgs(args);
17514
+ const memory = await adapter.updateMemory(parsedArgs, runtimeContext);
17515
+ const result = {
17516
+ action: 'update',
17517
+ status: 'updated',
17518
+ memory,
17519
+ };
17520
+ return JSON.stringify(result);
17521
+ }
17522
+ catch (error) {
17523
+ const result = {
17524
+ action: 'update',
17525
+ status: 'error',
17526
+ message: error instanceof Error ? error.message : String(error),
17527
+ };
17528
+ return JSON.stringify(result);
17529
+ }
17530
+ },
17531
+ async [DELETE_USER_MEMORY_TOOL_NAME](args) {
17532
+ const runtimeContext = resolveMemoryRuntimeContext(args);
17533
+ const { adapter, disabledResult } = getRuntimeAdapterOrDisabledResult('delete', runtimeContext);
17534
+ if (!adapter || disabledResult) {
17535
+ return JSON.stringify(disabledResult);
17536
+ }
17537
+ try {
17538
+ const parsedArgs = parseDeleteMemoryArgs(args);
17539
+ const deleted = await adapter.deleteMemory(parsedArgs, runtimeContext);
17540
+ const result = {
17541
+ action: 'delete',
17542
+ status: 'deleted',
17543
+ memoryId: deleted.id,
17544
+ };
17545
+ return JSON.stringify(result);
17546
+ }
17547
+ catch (error) {
17548
+ const result = {
17549
+ action: 'delete',
17550
+ status: 'error',
17551
+ message: error instanceof Error ? error.message : String(error),
17552
+ };
17553
+ return JSON.stringify(result);
17554
+ }
17555
+ },
17556
+ };
17091
17557
  }
17092
17558
  }
17093
17559
  /**
@@ -19073,7 +19539,8 @@ class TeamCommitmentDefinition extends BaseCommitmentDefinition {
19073
19539
  if (!trimmedContent) {
19074
19540
  return requirements;
19075
19541
  }
19076
- const teammates = parseTeamCommitmentContent(trimmedContent, { strict: true });
19542
+ // Keep TEAM resilient: unresolved/malformed teammate entries are skipped, valid ones are still registered.
19543
+ const teammates = parseTeamCommitmentContent(trimmedContent, { strict: false });
19077
19544
  if (teammates.length === 0) {
19078
19545
  return requirements;
19079
19546
  }
@@ -19199,14 +19666,30 @@ function buildTeammateRequest(message, context) {
19199
19666
  /**
19200
19667
  * Builds a minimal chat prompt for teammate calls.
19201
19668
  */
19202
- function buildTeammatePrompt(request) {
19669
+ function buildTeammatePrompt(request, runtimeContext) {
19203
19670
  return {
19204
19671
  title: 'Teammate consultation',
19205
19672
  modelRequirements: {
19206
19673
  modelVariant: 'CHAT',
19207
19674
  },
19208
19675
  content: request,
19209
- parameters: {},
19676
+ parameters: {
19677
+ [TOOL_RUNTIME_CONTEXT_PARAMETER]: serializeToolRuntimeContext(runtimeContext),
19678
+ },
19679
+ };
19680
+ }
19681
+ /**
19682
+ * Creates teammate runtime context and marks conversation as team-only memory-disabled.
19683
+ */
19684
+ function createTeamConversationRuntimeContext(value) {
19685
+ const runtimeContext = parseToolRuntimeContext(value) || {};
19686
+ return {
19687
+ ...runtimeContext,
19688
+ memory: {
19689
+ ...(runtimeContext.memory || {}),
19690
+ enabled: false,
19691
+ isTeamConversation: true,
19692
+ },
19210
19693
  };
19211
19694
  }
19212
19695
  /**
@@ -19250,7 +19733,7 @@ function createTeamToolFunction(entry) {
19250
19733
  let toolCalls;
19251
19734
  try {
19252
19735
  const remoteAgent = await getRemoteTeammateAgent(entry.teammate.url);
19253
- const prompt = buildTeammatePrompt(request);
19736
+ const prompt = buildTeammatePrompt(request, createTeamConversationRuntimeContext(args[TOOL_RUNTIME_CONTEXT_ARGUMENT]));
19254
19737
  const teammateResult = await remoteAgent.callChatModel(prompt);
19255
19738
  response = teammateResult.content || '';
19256
19739
  toolCalls =
@@ -19800,25 +20283,6 @@ class UseBrowserCommitmentDefinition extends BaseCommitmentDefinition {
19800
20283
  * Note: [💞] Ignore a discrepancy between file name and entity name
19801
20284
  */
19802
20285
 
19803
- /**
19804
- * @@@
19805
- *
19806
- * @private utility for commitments
19807
- */
19808
- function formatOptionalInstructionBlock(label, content) {
19809
- const trimmedContent = spaceTrim$1(content);
19810
- if (!trimmedContent) {
19811
- return '';
19812
- }
19813
- return spaceTrim$1((block) => `
19814
- - ${label}:
19815
- ${block(trimmedContent
19816
- .split(/\r?\n/)
19817
- .map((line) => `- ${line}`)
19818
- .join('\n'))}
19819
- `);
19820
- }
19821
-
19822
20286
  /**
19823
20287
  * Client-side safe wrapper for sending emails.
19824
20288
  *
@@ -27158,6 +27622,28 @@ function mapToolsToOpenAi(tools) {
27158
27622
  }));
27159
27623
  }
27160
27624
 
27625
+ /**
27626
+ * Builds a tool invocation script that injects hidden runtime context into tool args.
27627
+ *
27628
+ * @private utility of OpenAI tool execution wrappers
27629
+ */
27630
+ function buildToolInvocationScript(options) {
27631
+ const { functionName, functionArgsExpression } = options;
27632
+ return `
27633
+ const args = ${functionArgsExpression};
27634
+ const runtimeContextRaw =
27635
+ typeof ${TOOL_RUNTIME_CONTEXT_PARAMETER} === 'undefined'
27636
+ ? undefined
27637
+ : ${TOOL_RUNTIME_CONTEXT_PARAMETER};
27638
+
27639
+ if (runtimeContextRaw !== undefined && args && typeof args === 'object' && !Array.isArray(args)) {
27640
+ args.${TOOL_RUNTIME_CONTEXT_ARGUMENT} = runtimeContextRaw;
27641
+ }
27642
+
27643
+ return await ${functionName}(args);
27644
+ `;
27645
+ }
27646
+
27161
27647
  /**
27162
27648
  * Parses an OpenAI error message to identify which parameter is unsupported
27163
27649
  *
@@ -27511,10 +27997,10 @@ class OpenAiCompatibleExecutionTools {
27511
27997
  const scriptTool = scriptTools[0]; // <- TODO: [🧠] Which script tool to use?
27512
27998
  functionResponse = await scriptTool.execute({
27513
27999
  scriptLanguage: 'javascript',
27514
- script: `
27515
- const args = ${functionArgs};
27516
- return await ${functionName}(args);
27517
- `,
28000
+ script: buildToolInvocationScript({
28001
+ functionName,
28002
+ functionArgsExpression: functionArgs,
28003
+ }),
27518
28004
  parameters: prompt.parameters,
27519
28005
  });
27520
28006
  }
@@ -29684,10 +30170,10 @@ class OpenAiAssistantExecutionTools extends OpenAiVectorStoreHandler {
29684
30170
  const scriptTool = scriptTools[0]; // <- TODO: [🧠] Which script tool to use?
29685
30171
  functionResponse = await scriptTool.execute({
29686
30172
  scriptLanguage: 'javascript',
29687
- script: `
29688
- const args = ${JSON.stringify(functionArgs)};
29689
- return await ${functionName}(args);
29690
- `,
30173
+ script: buildToolInvocationScript({
30174
+ functionName,
30175
+ functionArgsExpression: JSON.stringify(functionArgs),
30176
+ }),
29691
30177
  parameters: prompt.parameters,
29692
30178
  });
29693
30179
  if (this.options.isVerbose) {
@@ -31646,14 +32132,42 @@ function removeCommentsFromSystemMessage(systemMessage) {
31646
32132
  }
31647
32133
 
31648
32134
  /**
31649
- * Creates agent model requirements using the new commitment system
32135
+ * Creates agent model requirements using the new commitment system.
32136
+ *
31650
32137
  * This function uses a reduce-like pattern where each commitment applies its changes
31651
- * to build the final requirements starting from a basic empty model
32138
+ * to build the final requirements starting from a basic empty model.
31652
32139
  *
31653
- * @public exported from `@promptbook/core`
32140
+ * @param agentSource - Agent source book to parse.
32141
+ * @param modelName - Optional override for the agent model name.
32142
+ * @param options - Additional options such as the agent reference resolver.
32143
+ *
32144
+ * @private @@@
32145
+ */
32146
+ const COMMITMENTS_WITH_AGENT_REFERENCES = new Set(['FROM', 'IMPORT', 'IMPORTS', 'TEAM']);
32147
+ /**
32148
+ * Returns a safe fallback content when a resolver fails to transform a reference commitment.
32149
+ *
32150
+ * @param commitmentType - Commitment being resolved.
32151
+ * @param originalContent - Original unresolved commitment content.
32152
+ * @returns Fallback content that keeps requirement creation resilient.
32153
+ */
32154
+ function getSafeReferenceCommitmentFallback(commitmentType, originalContent) {
32155
+ if (commitmentType === 'FROM') {
32156
+ return 'VOID';
32157
+ }
32158
+ if (commitmentType === 'IMPORT' || commitmentType === 'IMPORTS' || commitmentType === 'TEAM') {
32159
+ return '';
32160
+ }
32161
+ return originalContent;
32162
+ }
32163
+ /**
32164
+ * @@@
32165
+ *
32166
+ * @private @@@
31654
32167
  */
31655
- async function createAgentModelRequirementsWithCommitments(agentSource, modelName) {
32168
+ async function createAgentModelRequirementsWithCommitments(agentSource, modelName, options) {
31656
32169
  var _a;
32170
+ const agentReferenceResolver = options === null || options === void 0 ? void 0 : options.agentReferenceResolver;
31657
32171
  // Parse the agent source to extract commitments
31658
32172
  const parseResult = parseAgentSourceWithCommitments(agentSource);
31659
32173
  // Apply DELETE filtering: remove prior commitments tagged by parameters targeted by DELETE/CANCEL/DISCARD/REMOVE
@@ -31705,6 +32219,17 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
31705
32219
  // Apply each commitment in order using reduce-like pattern
31706
32220
  for (let i = 0; i < filteredCommitments.length; i++) {
31707
32221
  const commitment = filteredCommitments[i];
32222
+ const isReferenceCommitment = Boolean(agentReferenceResolver && COMMITMENTS_WITH_AGENT_REFERENCES.has(commitment.type));
32223
+ let commitmentContent = commitment.content;
32224
+ if (isReferenceCommitment && agentReferenceResolver) {
32225
+ try {
32226
+ commitmentContent = await agentReferenceResolver.resolveCommitmentContent(commitment.type, commitment.content);
32227
+ }
32228
+ catch (error) {
32229
+ console.warn(`Failed to resolve commitment references for ${commitment.type}, falling back to safe defaults:`, error);
32230
+ commitmentContent = getSafeReferenceCommitmentFallback(commitment.type, commitment.content);
32231
+ }
32232
+ }
31708
32233
  // CLOSED commitment should work only if its the last commitment in the book
31709
32234
  if (commitment.type === 'CLOSED' && i !== filteredCommitments.length - 1) {
31710
32235
  continue;
@@ -31712,7 +32237,7 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
31712
32237
  const definition = getCommitmentDefinition(commitment.type);
31713
32238
  if (definition) {
31714
32239
  try {
31715
- requirements = definition.applyToAgentModelRequirements(requirements, commitment.content);
32240
+ requirements = definition.applyToAgentModelRequirements(requirements, commitmentContent);
31716
32241
  }
31717
32242
  catch (error) {
31718
32243
  console.warn(`Failed to apply commitment ${commitment.type}:`, error);
@@ -31820,6 +32345,7 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
31820
32345
  systemMessage: requirements.systemMessage + '\n\n' + exampleInteractionsContent,
31821
32346
  };
31822
32347
  }
32348
+ requirements = await applyPendingInlineKnowledgeSources(requirements, options === null || options === void 0 ? void 0 : options.inlineKnowledgeSourceUploader);
31823
32349
  // Remove comment lines (lines starting with #) from the final system message
31824
32350
  // while preserving the original content with comments in metadata
31825
32351
  const cleanedSystemMessage = removeCommentsFromSystemMessage(requirements.systemMessage);
@@ -31828,6 +32354,54 @@ async function createAgentModelRequirementsWithCommitments(agentSource, modelNam
31828
32354
  systemMessage: cleanedSystemMessage,
31829
32355
  };
31830
32356
  }
32357
+ /**
32358
+ * @private Attempts to upload inline knowledge entries, falling back to legacy data URLs when the upload fails or is not configured.
32359
+ */
32360
+ async function applyPendingInlineKnowledgeSources(requirements, uploader) {
32361
+ var _a;
32362
+ const inlineSources = extractInlineKnowledgeSources(requirements._metadata);
32363
+ if (inlineSources.length === 0) {
32364
+ return requirements;
32365
+ }
32366
+ const knowledgeSources = [...((_a = requirements.knowledgeSources) !== null && _a !== void 0 ? _a : [])];
32367
+ for (const inlineSource of inlineSources) {
32368
+ const url = uploader
32369
+ ? await uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader)
32370
+ : inlineKnowledgeSourceToDataUrl(inlineSource);
32371
+ knowledgeSources.push(url);
32372
+ }
32373
+ return {
32374
+ ...requirements,
32375
+ knowledgeSources,
32376
+ _metadata: stripInlineKnowledgeMetadata(requirements._metadata),
32377
+ };
32378
+ }
32379
+ async function uploadInlineKnowledgeSourceWithFallback(inlineSource, uploader) {
32380
+ try {
32381
+ return await uploader(inlineSource);
32382
+ }
32383
+ catch (error) {
32384
+ console.error('[inline-knowledge] Failed to upload inline source', {
32385
+ filename: inlineSource.filename,
32386
+ error,
32387
+ });
32388
+ return inlineKnowledgeSourceToDataUrl(inlineSource);
32389
+ }
32390
+ }
32391
+ function extractInlineKnowledgeSources(metadata) {
32392
+ if (!metadata) {
32393
+ return [];
32394
+ }
32395
+ const value = metadata.inlineKnowledgeSources;
32396
+ return Array.isArray(value) ? value : [];
32397
+ }
32398
+ function stripInlineKnowledgeMetadata(metadata) {
32399
+ if (!metadata || !Object.prototype.hasOwnProperty.call(metadata, 'inlineKnowledgeSources')) {
32400
+ return metadata;
32401
+ }
32402
+ const { inlineKnowledgeSources: _unusedInlineKnowledgeSources, ...rest } = metadata;
32403
+ return Object.keys(rest).length > 0 ? rest : undefined;
32404
+ }
31831
32405
  /**
31832
32406
  * Mocked security check for imported files
31833
32407
  *
@@ -32171,23 +32745,28 @@ function normalizeSeparator(content) {
32171
32745
  */
32172
32746
 
32173
32747
  /**
32174
- * Creates model requirements for an agent based on its source
32748
+ * Creates model requirements for an agent based on its source.
32175
32749
  *
32176
32750
  * There are 2 similar functions:
32177
32751
  * - `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.
32178
32752
  * - `createAgentModelRequirements` which is an asynchronous function that creates model requirements it applies each commitment one by one and works asynchronous.
32179
32753
  *
32754
+ * @param agentSource - Book describing the agent.
32755
+ * @param modelName - Optional override for the agent's model.
32756
+ * @param availableModels - Models that could fulfill the agent.
32757
+ * @param llmTools - Execution tools used when selecting a best model.
32758
+ * @param options - Optional hooks such as the agent reference resolver.
32180
32759
  * @public exported from `@promptbook/core`
32181
32760
  */
32182
- async function createAgentModelRequirements(agentSource, modelName, availableModels, llmTools) {
32761
+ async function createAgentModelRequirements(agentSource, modelName, availableModels, llmTools, options) {
32183
32762
  // If availableModels are provided and no specific modelName is given,
32184
32763
  // use preparePersona to select the best model
32185
32764
  if (availableModels && !modelName && llmTools) {
32186
32765
  const selectedModelName = await selectBestModelUsingPersona(agentSource, llmTools);
32187
- return createAgentModelRequirementsWithCommitments(agentSource, selectedModelName);
32766
+ return createAgentModelRequirementsWithCommitments(agentSource, selectedModelName, options);
32188
32767
  }
32189
32768
  // Use the new commitment-based system with provided or default model
32190
- return createAgentModelRequirementsWithCommitments(agentSource, modelName);
32769
+ return createAgentModelRequirementsWithCommitments(agentSource, modelName, options);
32191
32770
  }
32192
32771
  /**
32193
32772
  * Selects the best model using the preparePersona function
@@ -33188,10 +33767,10 @@ class OpenAiAgentKitExecutionTools extends OpenAiVectorStoreHandler {
33188
33767
  try {
33189
33768
  return await scriptTool.execute({
33190
33769
  scriptLanguage: 'javascript',
33191
- script: `
33192
- const args = ${JSON.stringify(functionArgs)};
33193
- return await ${functionName}(args);
33194
- `,
33770
+ script: buildToolInvocationScript({
33771
+ functionName,
33772
+ functionArgsExpression: JSON.stringify(functionArgs),
33773
+ }),
33195
33774
  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 : {},
33196
33775
  });
33197
33776
  }
@@ -34222,6 +34801,20 @@ async function _Agent_selfLearnTeacher(prompt, result) {
34222
34801
  * TODO: [🧠][😰]Agent is not working with the parameters, should it be?
34223
34802
  */
34224
34803
 
34804
+ /**
34805
+ * Keep-alive helpers used for streaming chat responses.
34806
+ *
34807
+ * These constants coordinate the signal sent by the Agents Server streaming
34808
+ * endpoint and the parser in the SDK so we can distinguish between
34809
+ * real content and occasional pings.
34810
+ *
34811
+ * @private internal streaming helper for Promptbook chat connections
34812
+ */
34813
+ const CHAT_STREAM_KEEP_ALIVE_TOKEN = 'STREAM_KEEP_ALIVE';
34814
+ /**
34815
+ * Note: [💞] Ignore a discrepancy between file name and entity name
34816
+ */
34817
+
34225
34818
  /**
34226
34819
  * Resolve a remote META IMAGE value into an absolute URL when possible.
34227
34820
  */
@@ -34296,7 +34889,9 @@ class RemoteAgent extends Agent {
34296
34889
  static async connect(options) {
34297
34890
  var _a, _b, _c;
34298
34891
  const agentProfileUrl = `${options.agentUrl}/api/profile`;
34299
- const profileResponse = await fetch(agentProfileUrl);
34892
+ const profileResponse = await fetch(agentProfileUrl, {
34893
+ headers: attachClientVersionHeader(),
34894
+ });
34300
34895
  // <- TODO: [🐱‍🚀] What about closed-source agents?
34301
34896
  // <- TODO: [🐱‍🚀] Maybe use promptbookFetch
34302
34897
  if (!profileResponse.ok) {
@@ -34397,6 +34992,7 @@ class RemoteAgent extends Agent {
34397
34992
  }
34398
34993
  const response = await fetch(`${this.agentUrl}/api/voice`, {
34399
34994
  method: 'POST',
34995
+ headers: attachClientVersionHeader(),
34400
34996
  body: formData,
34401
34997
  });
34402
34998
  if (!response.ok) {
@@ -34426,13 +35022,14 @@ class RemoteAgent extends Agent {
34426
35022
  const chatPrompt = prompt;
34427
35023
  const bookResponse = await fetch(`${this.agentUrl}/api/chat`, {
34428
35024
  method: 'POST',
34429
- headers: {
35025
+ headers: attachClientVersionHeader({
34430
35026
  'Content-Type': 'application/json',
34431
- },
35027
+ }),
34432
35028
  body: JSON.stringify({
34433
35029
  message: prompt.content,
34434
35030
  thread: chatPrompt.thread,
34435
35031
  attachments: chatPrompt.attachments,
35032
+ parameters: chatPrompt.parameters,
34436
35033
  }),
34437
35034
  });
34438
35035
  // <- TODO: [🐱‍🚀] What about closed-source agents?
@@ -34514,6 +35111,9 @@ class RemoteAgent extends Agent {
34514
35111
  const lines = textChunk.split(/\r?\n/);
34515
35112
  for (const line of lines) {
34516
35113
  const trimmedLine = line.trim();
35114
+ if (trimmedLine === CHAT_STREAM_KEEP_ALIVE_TOKEN) {
35115
+ continue;
35116
+ }
34517
35117
  let isToolCallLine = false;
34518
35118
  if (trimmedLine.startsWith('{') && trimmedLine.endsWith('}')) {
34519
35119
  try {