@promptbook/remote-server 0.105.0-15 → 0.105.0-16

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
@@ -34,7 +34,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
34
34
  * @generated
35
35
  * @see https://github.com/webgptorg/promptbook
36
36
  */
37
- const PROMPTBOOK_ENGINE_VERSION = '0.105.0-15';
37
+ const PROMPTBOOK_ENGINE_VERSION = '0.105.0-16';
38
38
  /**
39
39
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
40
40
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -8033,6 +8033,18 @@ function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
8033
8033
  * TODO: [🌺] Use some intermediate util splitWords
8034
8034
  */
8035
8035
 
8036
+ /**
8037
+ * Computes SHA-256 hash of the given object
8038
+ *
8039
+ * @public exported from `@promptbook/utils`
8040
+ */
8041
+ function computeHash(value) {
8042
+ return SHA256(hexEncoder.parse(spaceTrim$2(valueToString(value)))).toString( /* hex */);
8043
+ }
8044
+ /**
8045
+ * TODO: [🥬][🥬] Use this ACRY
8046
+ */
8047
+
8036
8048
  /**
8037
8049
  * Makes first letter of a string lowercase
8038
8050
  *
@@ -11243,6 +11255,401 @@ class StyleCommitmentDefinition extends BaseCommitmentDefinition {
11243
11255
  * [💞] Ignore a discrepancy between file name and entity name
11244
11256
  */
11245
11257
 
11258
+ const urlRegex = /https?:\/\/[^\s]+/gi;
11259
+ const trailingPunctuationRegex = /[),.;!?]+$/;
11260
+ const clauseSeparators = ['.', '?', '!', ';', ','];
11261
+ const conjunctionSeparators = [' and ', ' or '];
11262
+ /**
11263
+ * Parses TEAM commitment content into teammates with instructions.
11264
+ *
11265
+ * @private
11266
+ */
11267
+ function parseTeamCommitmentContent(content, options = {}) {
11268
+ const { strict = false } = options;
11269
+ const lines = content
11270
+ .split('\n')
11271
+ .map((line) => line.trim())
11272
+ .filter(Boolean);
11273
+ const teammates = [];
11274
+ const seenUrls = new Set();
11275
+ for (const line of lines) {
11276
+ const matches = Array.from(line.matchAll(urlRegex));
11277
+ if (matches.length === 0) {
11278
+ if (strict) {
11279
+ throw new Error(`TEAM commitment expects at least one agent URL, got: "${line}"`);
11280
+ }
11281
+ continue;
11282
+ }
11283
+ for (const [matchIndex, match] of matches.entries()) {
11284
+ const rawUrl = match[0] || '';
11285
+ const cleanedUrl = rawUrl.replace(trailingPunctuationRegex, '');
11286
+ if (!isValidAgentUrl(cleanedUrl)) {
11287
+ if (strict) {
11288
+ throw new Error(`Invalid agent URL in TEAM commitment: "${cleanedUrl}"`);
11289
+ }
11290
+ continue;
11291
+ }
11292
+ if (seenUrls.has(cleanedUrl)) {
11293
+ continue;
11294
+ }
11295
+ seenUrls.add(cleanedUrl);
11296
+ const instructionContext = extractInstructionContext(line, matches, matchIndex);
11297
+ const instructions = normalizeInstructionText(instructionContext);
11298
+ const label = createTeammateLabel(cleanedUrl);
11299
+ teammates.push({
11300
+ url: cleanedUrl,
11301
+ label,
11302
+ instructions,
11303
+ });
11304
+ }
11305
+ }
11306
+ return teammates;
11307
+ }
11308
+ function extractInstructionContext(line, matches, matchIndex) {
11309
+ var _a;
11310
+ const match = matches[matchIndex];
11311
+ if (!match || match.index === undefined) {
11312
+ return line.trim();
11313
+ }
11314
+ const rawUrl = match[0] || '';
11315
+ const matchStart = match.index;
11316
+ const matchEnd = matchStart + rawUrl.length;
11317
+ const previousMatch = matches[matchIndex - 1];
11318
+ const nextMatch = matches[matchIndex + 1];
11319
+ const previousEnd = previousMatch && previousMatch.index !== undefined ? previousMatch.index + (((_a = previousMatch[0]) === null || _a === void 0 ? void 0 : _a.length) || 0) : 0;
11320
+ const nextStart = nextMatch && nextMatch.index !== undefined ? nextMatch.index : line.length;
11321
+ const rawPrefix = line.slice(previousEnd, matchStart);
11322
+ const rawSuffix = line.slice(matchEnd, nextStart);
11323
+ const prefix = trimAfterLastDelimiter(rawPrefix);
11324
+ const suffix = trimBeforeLastDelimiter(rawSuffix);
11325
+ if (normalizeInstructionText(suffix)) {
11326
+ return suffix;
11327
+ }
11328
+ if (normalizeInstructionText(prefix)) {
11329
+ return prefix;
11330
+ }
11331
+ return `${prefix} ${suffix}`.trim();
11332
+ }
11333
+ function trimAfterLastDelimiter(text) {
11334
+ const match = findLastDelimiter(text);
11335
+ if (!match) {
11336
+ return text;
11337
+ }
11338
+ return text.slice(match.index + match.length);
11339
+ }
11340
+ function trimBeforeLastDelimiter(text) {
11341
+ const cleaned = text.replace(/^[,;:]\s*/g, '');
11342
+ const match = findLastDelimiter(cleaned);
11343
+ if (!match || match.index <= 0) {
11344
+ return cleaned;
11345
+ }
11346
+ return cleaned.slice(0, match.index);
11347
+ }
11348
+ function findLastDelimiter(text) {
11349
+ let bestIndex = -1;
11350
+ let bestLength = 0;
11351
+ for (const separator of clauseSeparators) {
11352
+ const index = text.lastIndexOf(separator);
11353
+ if (index > bestIndex) {
11354
+ bestIndex = index;
11355
+ bestLength = separator.length;
11356
+ }
11357
+ }
11358
+ const lowerText = text.toLowerCase();
11359
+ for (const separator of conjunctionSeparators) {
11360
+ const index = lowerText.lastIndexOf(separator);
11361
+ if (index > bestIndex) {
11362
+ bestIndex = index;
11363
+ bestLength = separator.length;
11364
+ }
11365
+ }
11366
+ if (bestIndex === -1) {
11367
+ return null;
11368
+ }
11369
+ return { index: bestIndex, length: bestLength };
11370
+ }
11371
+ function normalizeInstructionText(text) {
11372
+ if (!text) {
11373
+ return '';
11374
+ }
11375
+ const withoutUrls = text.replace(urlRegex, '');
11376
+ let normalized = normalizeWhitespaces(withoutUrls).trim();
11377
+ normalized = normalized.replace(/^[,;:]\s*/g, '');
11378
+ normalized = normalized.replace(/^(and|or|the|a|an)\s+/i, '');
11379
+ normalized = normalized.replace(/\s*[,;:]\s*$/g, '');
11380
+ normalized = normalized.replace(/\s+(and|or)\s*$/i, '');
11381
+ normalized = normalizeWhitespaces(normalized).trim();
11382
+ return normalized;
11383
+ }
11384
+ function createTeammateLabel(url) {
11385
+ try {
11386
+ const parsed = new URL(url);
11387
+ const pathParts = parsed.pathname.split('/').filter(Boolean);
11388
+ const lastPart = pathParts[pathParts.length - 1] || parsed.hostname;
11389
+ const decoded = decodeURIComponent(lastPart);
11390
+ const spaced = decoded.replace(/[-_]+/g, ' ').trim();
11391
+ if (!spaced) {
11392
+ return parsed.hostname;
11393
+ }
11394
+ return spaced
11395
+ .split(' ')
11396
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
11397
+ .join(' ');
11398
+ }
11399
+ catch (error) {
11400
+ return url;
11401
+ }
11402
+ }
11403
+ /**
11404
+ * Note: [💞] Ignore a discrepancy between file name and entity name
11405
+ */
11406
+
11407
+ const TEAM_TOOL_PREFIX = 'team_chat_';
11408
+ const teamToolFunctions = {};
11409
+ const teamToolTitles = {};
11410
+ /**
11411
+ * TEAM commitment definition
11412
+ *
11413
+ * The `TEAM` commitment defines teammates that the agent can consult via tools.
11414
+ *
11415
+ * Example usage in agent source:
11416
+ *
11417
+ * ```book
11418
+ * TEAM https://agents.ptbk.ik/agents/joe-green
11419
+ * TEAM You can talk with http://localhost:4440/agents/GMw67JN8TXxN7y to discuss the legal aspects.
11420
+ * ```
11421
+ *
11422
+ * @private [??] Maybe export the commitments through some package
11423
+ */
11424
+ class TeamCommitmentDefinition extends BaseCommitmentDefinition {
11425
+ constructor() {
11426
+ super('TEAM');
11427
+ }
11428
+ /**
11429
+ * Short one-line description of TEAM.
11430
+ */
11431
+ get description() {
11432
+ return 'Enable the agent to consult teammate agents via dedicated tools.';
11433
+ }
11434
+ /**
11435
+ * Icon for this commitment.
11436
+ */
11437
+ get icon() {
11438
+ return '??';
11439
+ }
11440
+ /**
11441
+ * Markdown documentation for TEAM commitment.
11442
+ */
11443
+ get documentation() {
11444
+ return spaceTrim$1(`
11445
+ # TEAM
11446
+
11447
+ Registers teammate agents that the current agent can consult via tools.
11448
+
11449
+ ## Examples
11450
+
11451
+ \`\`\`book
11452
+ Legal Assistant
11453
+
11454
+ PERSONA An expert software developer
11455
+ TEAM You can talk with http://localhost:4440/agents/GMw67JN8TXxN7y to discuss the legal aspects.
11456
+ \`\`\`
11457
+ `);
11458
+ }
11459
+ applyToAgentModelRequirements(requirements, content) {
11460
+ var _a, _b;
11461
+ const trimmedContent = content.trim();
11462
+ if (!trimmedContent) {
11463
+ return requirements;
11464
+ }
11465
+ const teammates = parseTeamCommitmentContent(trimmedContent, { strict: true });
11466
+ if (teammates.length === 0) {
11467
+ return requirements;
11468
+ }
11469
+ const agentName = ((_a = requirements.metadata) === null || _a === void 0 ? void 0 : _a.agentName) || 'Agent';
11470
+ const teamEntries = teammates.map((teammate) => ({
11471
+ toolName: createTeamToolName(teammate.url),
11472
+ teammate,
11473
+ agentName,
11474
+ }));
11475
+ for (const entry of teamEntries) {
11476
+ registerTeamTool(entry);
11477
+ }
11478
+ const existingTools = requirements.tools || [];
11479
+ const updatedTools = [...existingTools];
11480
+ for (const entry of teamEntries) {
11481
+ if (updatedTools.some((tool) => tool.name === entry.toolName)) {
11482
+ continue;
11483
+ }
11484
+ const instructionSuffix = entry.teammate.instructions
11485
+ ? `Use when: ${entry.teammate.instructions}`
11486
+ : 'Use when their expertise is needed.';
11487
+ updatedTools.push({
11488
+ name: entry.toolName,
11489
+ description: spaceTrim$1(`
11490
+ Consult teammate ${entry.teammate.label} (${entry.teammate.url}).
11491
+ ${instructionSuffix}
11492
+ `),
11493
+ parameters: {
11494
+ type: 'object',
11495
+ properties: {
11496
+ message: {
11497
+ type: 'string',
11498
+ description: 'Question or request to send to the teammate.',
11499
+ },
11500
+ context: {
11501
+ type: 'string',
11502
+ description: 'Optional background context for the teammate.',
11503
+ },
11504
+ },
11505
+ required: ['message'],
11506
+ },
11507
+ });
11508
+ }
11509
+ const existingTeammates = ((_b = requirements.metadata) === null || _b === void 0 ? void 0 : _b.teammates) || [];
11510
+ const updatedTeammates = [...existingTeammates];
11511
+ for (const entry of teamEntries) {
11512
+ if (updatedTeammates.some((existing) => existing.url === entry.teammate.url)) {
11513
+ continue;
11514
+ }
11515
+ updatedTeammates.push({
11516
+ url: entry.teammate.url,
11517
+ label: entry.teammate.label,
11518
+ instructions: entry.teammate.instructions || undefined,
11519
+ toolName: entry.toolName,
11520
+ });
11521
+ }
11522
+ const teamSystemMessage = spaceTrim$1((block) => `
11523
+ Teammates:
11524
+ ${block(teamEntries
11525
+ .map((entry) => {
11526
+ const whenToConsult = entry.teammate.instructions || 'Use when their expertise is needed.';
11527
+ return spaceTrim$1(() => `
11528
+ - ${entry.teammate.label} (${entry.teammate.url})
11529
+ - Tool: "${entry.toolName}"
11530
+ - When to consult: ${whenToConsult}
11531
+ `);
11532
+ })
11533
+ .join('\n'))}
11534
+ `);
11535
+ return this.appendToSystemMessage({
11536
+ ...requirements,
11537
+ tools: updatedTools,
11538
+ metadata: {
11539
+ ...requirements.metadata,
11540
+ teammates: updatedTeammates,
11541
+ },
11542
+ }, teamSystemMessage);
11543
+ }
11544
+ /**
11545
+ * Gets human-readable titles for tool functions provided by this commitment.
11546
+ */
11547
+ getToolTitles() {
11548
+ return { ...teamToolTitles };
11549
+ }
11550
+ /**
11551
+ * Gets tool function implementations for teammate tools.
11552
+ */
11553
+ getToolFunctions() {
11554
+ return { ...teamToolFunctions };
11555
+ }
11556
+ }
11557
+ function createTeamToolName(url) {
11558
+ const hash = computeHash(url).substring(0, 10);
11559
+ return `${TEAM_TOOL_PREFIX}${hash}`;
11560
+ }
11561
+ function registerTeamTool(entry) {
11562
+ teamToolFunctions[entry.toolName] = createTeamToolFunction(entry);
11563
+ teamToolTitles[entry.toolName] = `Consult ${entry.teammate.label}`;
11564
+ }
11565
+ function createTeamToolFunction(entry) {
11566
+ return async (args) => {
11567
+ const message = args.message || args.question || '';
11568
+ if (!message) {
11569
+ const result = {
11570
+ error: 'Message is required to contact teammate.',
11571
+ teammate: {
11572
+ url: entry.teammate.url,
11573
+ label: entry.teammate.label,
11574
+ instructions: entry.teammate.instructions,
11575
+ toolName: entry.toolName,
11576
+ },
11577
+ };
11578
+ return JSON.stringify(result);
11579
+ }
11580
+ const request = args.context ? `${message}\n\nContext:\n${args.context}` : message;
11581
+ let response = '';
11582
+ let error = null;
11583
+ try {
11584
+ response = await fetchTeammateResponse(entry.teammate.url, request);
11585
+ }
11586
+ catch (err) {
11587
+ error = err instanceof Error ? err.message : String(err);
11588
+ }
11589
+ const teammateReply = response || (error ? `Unable to reach teammate. Error: ${error}` : 'No response received.');
11590
+ const result = {
11591
+ teammate: {
11592
+ url: entry.teammate.url,
11593
+ label: entry.teammate.label,
11594
+ instructions: entry.teammate.instructions,
11595
+ toolName: entry.toolName,
11596
+ },
11597
+ request,
11598
+ response: teammateReply,
11599
+ error,
11600
+ conversation: [
11601
+ {
11602
+ sender: 'AGENT',
11603
+ name: entry.agentName,
11604
+ content: request,
11605
+ },
11606
+ {
11607
+ sender: 'TEAMMATE',
11608
+ name: entry.teammate.label,
11609
+ content: teammateReply,
11610
+ },
11611
+ ],
11612
+ };
11613
+ return JSON.stringify(result);
11614
+ };
11615
+ }
11616
+ async function fetchTeammateResponse(agentUrl, message) {
11617
+ const url = `${agentUrl.replace(/\/$/, '')}/api/chat`;
11618
+ const response = await promptbookFetch(url, {
11619
+ method: 'POST',
11620
+ headers: {
11621
+ 'Content-Type': 'application/json',
11622
+ },
11623
+ body: JSON.stringify({ message }),
11624
+ });
11625
+ if (!response.ok) {
11626
+ throw new Error(`Teammate request failed: ${response.status} ${response.statusText}`);
11627
+ }
11628
+ const rawText = await response.text();
11629
+ return stripToolCallLines(rawText).trim();
11630
+ }
11631
+ function stripToolCallLines(text) {
11632
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
11633
+ return lines
11634
+ .filter((line) => {
11635
+ const trimmed = line.trim();
11636
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) {
11637
+ return true;
11638
+ }
11639
+ try {
11640
+ const parsed = JSON.parse(trimmed);
11641
+ return !('toolCalls' in parsed);
11642
+ }
11643
+ catch (_a) {
11644
+ return true;
11645
+ }
11646
+ })
11647
+ .join('\n');
11648
+ }
11649
+ /**
11650
+ * Note: [💞] Ignore a discrepancy between file name and entity name
11651
+ */
11652
+
11246
11653
  /**
11247
11654
  * USE commitment definition
11248
11655
  *
@@ -12237,6 +12644,7 @@ const COMMITMENT_REGISTRY = [
12237
12644
  new DictionaryCommitmentDefinition(),
12238
12645
  new OpenCommitmentDefinition(),
12239
12646
  new ClosedCommitmentDefinition(),
12647
+ new TeamCommitmentDefinition(),
12240
12648
  new UseBrowserCommitmentDefinition(),
12241
12649
  new UseSearchEngineCommitmentDefinition(),
12242
12650
  new UseTimeCommitmentDefinition(),