@promptbook/cli 0.105.0-15 → 0.105.0-17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.es.js CHANGED
@@ -47,7 +47,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
47
47
  * @generated
48
48
  * @see https://github.com/webgptorg/promptbook
49
49
  */
50
- const PROMPTBOOK_ENGINE_VERSION = '0.105.0-15';
50
+ const PROMPTBOOK_ENGINE_VERSION = '0.105.0-17';
51
51
  /**
52
52
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
53
53
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -16359,6 +16359,401 @@ class StyleCommitmentDefinition extends BaseCommitmentDefinition {
16359
16359
  * [💞] Ignore a discrepancy between file name and entity name
16360
16360
  */
16361
16361
 
16362
+ const urlRegex = /https?:\/\/[^\s]+/gi;
16363
+ const trailingPunctuationRegex = /[),.;!?]+$/;
16364
+ const clauseSeparators = ['.', '?', '!', ';', ','];
16365
+ const conjunctionSeparators = [' and ', ' or '];
16366
+ /**
16367
+ * Parses TEAM commitment content into teammates with instructions.
16368
+ *
16369
+ * @private
16370
+ */
16371
+ function parseTeamCommitmentContent(content, options = {}) {
16372
+ const { strict = false } = options;
16373
+ const lines = content
16374
+ .split('\n')
16375
+ .map((line) => line.trim())
16376
+ .filter(Boolean);
16377
+ const teammates = [];
16378
+ const seenUrls = new Set();
16379
+ for (const line of lines) {
16380
+ const matches = Array.from(line.matchAll(urlRegex));
16381
+ if (matches.length === 0) {
16382
+ if (strict) {
16383
+ throw new Error(`TEAM commitment expects at least one agent URL, got: "${line}"`);
16384
+ }
16385
+ continue;
16386
+ }
16387
+ for (const [matchIndex, match] of matches.entries()) {
16388
+ const rawUrl = match[0] || '';
16389
+ const cleanedUrl = rawUrl.replace(trailingPunctuationRegex, '');
16390
+ if (!isValidAgentUrl(cleanedUrl)) {
16391
+ if (strict) {
16392
+ throw new Error(`Invalid agent URL in TEAM commitment: "${cleanedUrl}"`);
16393
+ }
16394
+ continue;
16395
+ }
16396
+ if (seenUrls.has(cleanedUrl)) {
16397
+ continue;
16398
+ }
16399
+ seenUrls.add(cleanedUrl);
16400
+ const instructionContext = extractInstructionContext(line, matches, matchIndex);
16401
+ const instructions = normalizeInstructionText(instructionContext);
16402
+ const label = createTeammateLabel(cleanedUrl);
16403
+ teammates.push({
16404
+ url: cleanedUrl,
16405
+ label,
16406
+ instructions,
16407
+ });
16408
+ }
16409
+ }
16410
+ return teammates;
16411
+ }
16412
+ function extractInstructionContext(line, matches, matchIndex) {
16413
+ var _a;
16414
+ const match = matches[matchIndex];
16415
+ if (!match || match.index === undefined) {
16416
+ return line.trim();
16417
+ }
16418
+ const rawUrl = match[0] || '';
16419
+ const matchStart = match.index;
16420
+ const matchEnd = matchStart + rawUrl.length;
16421
+ const previousMatch = matches[matchIndex - 1];
16422
+ const nextMatch = matches[matchIndex + 1];
16423
+ const previousEnd = previousMatch && previousMatch.index !== undefined ? previousMatch.index + (((_a = previousMatch[0]) === null || _a === void 0 ? void 0 : _a.length) || 0) : 0;
16424
+ const nextStart = nextMatch && nextMatch.index !== undefined ? nextMatch.index : line.length;
16425
+ const rawPrefix = line.slice(previousEnd, matchStart);
16426
+ const rawSuffix = line.slice(matchEnd, nextStart);
16427
+ const prefix = trimAfterLastDelimiter(rawPrefix);
16428
+ const suffix = trimBeforeLastDelimiter(rawSuffix);
16429
+ if (normalizeInstructionText(suffix)) {
16430
+ return suffix;
16431
+ }
16432
+ if (normalizeInstructionText(prefix)) {
16433
+ return prefix;
16434
+ }
16435
+ return `${prefix} ${suffix}`.trim();
16436
+ }
16437
+ function trimAfterLastDelimiter(text) {
16438
+ const match = findLastDelimiter(text);
16439
+ if (!match) {
16440
+ return text;
16441
+ }
16442
+ return text.slice(match.index + match.length);
16443
+ }
16444
+ function trimBeforeLastDelimiter(text) {
16445
+ const cleaned = text.replace(/^[,;:]\s*/g, '');
16446
+ const match = findLastDelimiter(cleaned);
16447
+ if (!match || match.index <= 0) {
16448
+ return cleaned;
16449
+ }
16450
+ return cleaned.slice(0, match.index);
16451
+ }
16452
+ function findLastDelimiter(text) {
16453
+ let bestIndex = -1;
16454
+ let bestLength = 0;
16455
+ for (const separator of clauseSeparators) {
16456
+ const index = text.lastIndexOf(separator);
16457
+ if (index > bestIndex) {
16458
+ bestIndex = index;
16459
+ bestLength = separator.length;
16460
+ }
16461
+ }
16462
+ const lowerText = text.toLowerCase();
16463
+ for (const separator of conjunctionSeparators) {
16464
+ const index = lowerText.lastIndexOf(separator);
16465
+ if (index > bestIndex) {
16466
+ bestIndex = index;
16467
+ bestLength = separator.length;
16468
+ }
16469
+ }
16470
+ if (bestIndex === -1) {
16471
+ return null;
16472
+ }
16473
+ return { index: bestIndex, length: bestLength };
16474
+ }
16475
+ function normalizeInstructionText(text) {
16476
+ if (!text) {
16477
+ return '';
16478
+ }
16479
+ const withoutUrls = text.replace(urlRegex, '');
16480
+ let normalized = normalizeWhitespaces(withoutUrls).trim();
16481
+ normalized = normalized.replace(/^[,;:]\s*/g, '');
16482
+ normalized = normalized.replace(/^(and|or|the|a|an)\s+/i, '');
16483
+ normalized = normalized.replace(/\s*[,;:]\s*$/g, '');
16484
+ normalized = normalized.replace(/\s+(and|or)\s*$/i, '');
16485
+ normalized = normalizeWhitespaces(normalized).trim();
16486
+ return normalized;
16487
+ }
16488
+ function createTeammateLabel(url) {
16489
+ try {
16490
+ const parsed = new URL(url);
16491
+ const pathParts = parsed.pathname.split('/').filter(Boolean);
16492
+ const lastPart = pathParts[pathParts.length - 1] || parsed.hostname;
16493
+ const decoded = decodeURIComponent(lastPart);
16494
+ const spaced = decoded.replace(/[-_]+/g, ' ').trim();
16495
+ if (!spaced) {
16496
+ return parsed.hostname;
16497
+ }
16498
+ return spaced
16499
+ .split(' ')
16500
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
16501
+ .join(' ');
16502
+ }
16503
+ catch (error) {
16504
+ return url;
16505
+ }
16506
+ }
16507
+ /**
16508
+ * Note: [💞] Ignore a discrepancy between file name and entity name
16509
+ */
16510
+
16511
+ const TEAM_TOOL_PREFIX = 'team_chat_';
16512
+ const teamToolFunctions = {};
16513
+ const teamToolTitles = {};
16514
+ /**
16515
+ * TEAM commitment definition
16516
+ *
16517
+ * The `TEAM` commitment defines teammates that the agent can consult via tools.
16518
+ *
16519
+ * Example usage in agent source:
16520
+ *
16521
+ * ```book
16522
+ * TEAM https://agents.ptbk.ik/agents/joe-green
16523
+ * TEAM You can talk with http://localhost:4440/agents/GMw67JN8TXxN7y to discuss the legal aspects.
16524
+ * ```
16525
+ *
16526
+ * @private [??] Maybe export the commitments through some package
16527
+ */
16528
+ class TeamCommitmentDefinition extends BaseCommitmentDefinition {
16529
+ constructor() {
16530
+ super('TEAM');
16531
+ }
16532
+ /**
16533
+ * Short one-line description of TEAM.
16534
+ */
16535
+ get description() {
16536
+ return 'Enable the agent to consult teammate agents via dedicated tools.';
16537
+ }
16538
+ /**
16539
+ * Icon for this commitment.
16540
+ */
16541
+ get icon() {
16542
+ return '??';
16543
+ }
16544
+ /**
16545
+ * Markdown documentation for TEAM commitment.
16546
+ */
16547
+ get documentation() {
16548
+ return spaceTrim$1(`
16549
+ # TEAM
16550
+
16551
+ Registers teammate agents that the current agent can consult via tools.
16552
+
16553
+ ## Examples
16554
+
16555
+ \`\`\`book
16556
+ Legal Assistant
16557
+
16558
+ PERSONA An expert software developer
16559
+ TEAM You can talk with http://localhost:4440/agents/GMw67JN8TXxN7y to discuss the legal aspects.
16560
+ \`\`\`
16561
+ `);
16562
+ }
16563
+ applyToAgentModelRequirements(requirements, content) {
16564
+ var _a, _b;
16565
+ const trimmedContent = content.trim();
16566
+ if (!trimmedContent) {
16567
+ return requirements;
16568
+ }
16569
+ const teammates = parseTeamCommitmentContent(trimmedContent, { strict: true });
16570
+ if (teammates.length === 0) {
16571
+ return requirements;
16572
+ }
16573
+ const agentName = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.agentName) || 'Agent';
16574
+ const teamEntries = teammates.map((teammate) => ({
16575
+ toolName: createTeamToolName(teammate.url),
16576
+ teammate,
16577
+ agentName,
16578
+ }));
16579
+ for (const entry of teamEntries) {
16580
+ registerTeamTool(entry);
16581
+ }
16582
+ const existingTools = requirements.tools || [];
16583
+ const updatedTools = [...existingTools];
16584
+ for (const entry of teamEntries) {
16585
+ if (updatedTools.some((tool) => tool.name === entry.toolName)) {
16586
+ continue;
16587
+ }
16588
+ const instructionSuffix = entry.teammate.instructions
16589
+ ? `Use when: ${entry.teammate.instructions}`
16590
+ : 'Use when their expertise is needed.';
16591
+ updatedTools.push({
16592
+ name: entry.toolName,
16593
+ description: spaceTrim$1(`
16594
+ Consult teammate ${entry.teammate.label} (${entry.teammate.url}).
16595
+ ${instructionSuffix}
16596
+ `),
16597
+ parameters: {
16598
+ type: 'object',
16599
+ properties: {
16600
+ message: {
16601
+ type: 'string',
16602
+ description: 'Question or request to send to the teammate.',
16603
+ },
16604
+ context: {
16605
+ type: 'string',
16606
+ description: 'Optional background context for the teammate.',
16607
+ },
16608
+ },
16609
+ required: ['message'],
16610
+ },
16611
+ });
16612
+ }
16613
+ const existingTeammates = ((_b = requirements.metadata) === null || _b === void 0 ? void 0 : _b.teammates) || [];
16614
+ const updatedTeammates = [...existingTeammates];
16615
+ for (const entry of teamEntries) {
16616
+ if (updatedTeammates.some((existing) => existing.url === entry.teammate.url)) {
16617
+ continue;
16618
+ }
16619
+ updatedTeammates.push({
16620
+ url: entry.teammate.url,
16621
+ label: entry.teammate.label,
16622
+ instructions: entry.teammate.instructions || undefined,
16623
+ toolName: entry.toolName,
16624
+ });
16625
+ }
16626
+ const teamSystemMessage = spaceTrim$1((block) => `
16627
+ Teammates:
16628
+ ${block(teamEntries
16629
+ .map((entry) => {
16630
+ const whenToConsult = entry.teammate.instructions || 'Use when their expertise is needed.';
16631
+ return spaceTrim$1(() => `
16632
+ - ${entry.teammate.label} (${entry.teammate.url})
16633
+ - Tool: "${entry.toolName}"
16634
+ - When to consult: ${whenToConsult}
16635
+ `);
16636
+ })
16637
+ .join('\n'))}
16638
+ `);
16639
+ return this.appendToSystemMessage({
16640
+ ...requirements,
16641
+ tools: updatedTools,
16642
+ metadata: {
16643
+ ...requirements.metadata,
16644
+ teammates: updatedTeammates,
16645
+ },
16646
+ }, teamSystemMessage);
16647
+ }
16648
+ /**
16649
+ * Gets human-readable titles for tool functions provided by this commitment.
16650
+ */
16651
+ getToolTitles() {
16652
+ return { ...teamToolTitles };
16653
+ }
16654
+ /**
16655
+ * Gets tool function implementations for teammate tools.
16656
+ */
16657
+ getToolFunctions() {
16658
+ return { ...teamToolFunctions };
16659
+ }
16660
+ }
16661
+ function createTeamToolName(url) {
16662
+ const hash = computeHash(url).substring(0, 10);
16663
+ return `${TEAM_TOOL_PREFIX}${hash}`;
16664
+ }
16665
+ function registerTeamTool(entry) {
16666
+ teamToolFunctions[entry.toolName] = createTeamToolFunction(entry);
16667
+ teamToolTitles[entry.toolName] = `Consult ${entry.teammate.label}`;
16668
+ }
16669
+ function createTeamToolFunction(entry) {
16670
+ return async (args) => {
16671
+ const message = args.message || args.question || '';
16672
+ if (!message) {
16673
+ const result = {
16674
+ error: 'Message is required to contact teammate.',
16675
+ teammate: {
16676
+ url: entry.teammate.url,
16677
+ label: entry.teammate.label,
16678
+ instructions: entry.teammate.instructions,
16679
+ toolName: entry.toolName,
16680
+ },
16681
+ };
16682
+ return JSON.stringify(result);
16683
+ }
16684
+ const request = args.context ? `${message}\n\nContext:\n${args.context}` : message;
16685
+ let response = '';
16686
+ let error = null;
16687
+ try {
16688
+ response = await fetchTeammateResponse(entry.teammate.url, request);
16689
+ }
16690
+ catch (err) {
16691
+ error = err instanceof Error ? err.message : String(err);
16692
+ }
16693
+ const teammateReply = response || (error ? `Unable to reach teammate. Error: ${error}` : 'No response received.');
16694
+ const result = {
16695
+ teammate: {
16696
+ url: entry.teammate.url,
16697
+ label: entry.teammate.label,
16698
+ instructions: entry.teammate.instructions,
16699
+ toolName: entry.toolName,
16700
+ },
16701
+ request,
16702
+ response: teammateReply,
16703
+ error,
16704
+ conversation: [
16705
+ {
16706
+ sender: 'AGENT',
16707
+ name: entry.agentName,
16708
+ content: request,
16709
+ },
16710
+ {
16711
+ sender: 'TEAMMATE',
16712
+ name: entry.teammate.label,
16713
+ content: teammateReply,
16714
+ },
16715
+ ],
16716
+ };
16717
+ return JSON.stringify(result);
16718
+ };
16719
+ }
16720
+ async function fetchTeammateResponse(agentUrl, message) {
16721
+ const url = `${agentUrl.replace(/\/$/, '')}/api/chat`;
16722
+ const response = await promptbookFetch(url, {
16723
+ method: 'POST',
16724
+ headers: {
16725
+ 'Content-Type': 'application/json',
16726
+ },
16727
+ body: JSON.stringify({ message }),
16728
+ });
16729
+ if (!response.ok) {
16730
+ throw new Error(`Teammate request failed: ${response.status} ${response.statusText}`);
16731
+ }
16732
+ const rawText = await response.text();
16733
+ return stripToolCallLines(rawText).trim();
16734
+ }
16735
+ function stripToolCallLines(text) {
16736
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
16737
+ return lines
16738
+ .filter((line) => {
16739
+ const trimmed = line.trim();
16740
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) {
16741
+ return true;
16742
+ }
16743
+ try {
16744
+ const parsed = JSON.parse(trimmed);
16745
+ return !('toolCalls' in parsed);
16746
+ }
16747
+ catch (_a) {
16748
+ return true;
16749
+ }
16750
+ })
16751
+ .join('\n');
16752
+ }
16753
+ /**
16754
+ * Note: [💞] Ignore a discrepancy between file name and entity name
16755
+ */
16756
+
16362
16757
  /**
16363
16758
  * USE commitment definition
16364
16759
  *
@@ -17353,6 +17748,7 @@ const COMMITMENT_REGISTRY = [
17353
17748
  new DictionaryCommitmentDefinition(),
17354
17749
  new OpenCommitmentDefinition(),
17355
17750
  new ClosedCommitmentDefinition(),
17751
+ new TeamCommitmentDefinition(),
17356
17752
  new UseBrowserCommitmentDefinition(),
17357
17753
  new UseSearchEngineCommitmentDefinition(),
17358
17754
  new UseTimeCommitmentDefinition(),
@@ -25720,6 +26116,7 @@ class OpenAiAssistantExecutionTools extends OpenAiExecutionTools {
25720
26116
  */
25721
26117
  const DISCRIMINANT = 'OPEN_AI_ASSISTANT_V1';
25722
26118
  /**
26119
+ * TODO: !!!!! [✨🥚] Knowledge should work both with and without scrapers
25723
26120
  * TODO: [🙎] In `OpenAiAssistantExecutionTools` Allow to create abstract assistants with `isCreatingNewAssistantsAllowed`
25724
26121
  * TODO: [🧠][🧙‍♂️] Maybe there can be some wizard for those who want to use just OpenAI
25725
26122
  * TODO: Maybe make custom OpenAiError
@@ -28047,6 +28444,18 @@ function parseAgentSource(agentSource) {
28047
28444
  });
28048
28445
  continue;
28049
28446
  }
28447
+ if (commitment.type === 'TEAM') {
28448
+ const teammates = parseTeamCommitmentContent(commitment.content);
28449
+ for (const teammate of teammates) {
28450
+ capabilities.push({
28451
+ type: 'team',
28452
+ label: teammate.label,
28453
+ iconName: 'Users',
28454
+ agentUrl: teammate.url,
28455
+ });
28456
+ }
28457
+ continue;
28458
+ }
28050
28459
  if (commitment.type === 'KNOWLEDGE') {
28051
28460
  const content = spaceTrim$2(commitment.content).split('\n')[0] || '';
28052
28461
  let label = content;