briyah 2.0.5 → 2.0.7
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/README.md +105 -0
- package/data/common/prompts/moderate.json +34 -0
- package/data/common/prompts/moderate.prompt +136 -0
- package/data/packs/dnd5e/pack.json +7 -1
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +16 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +23 -0
- package/dist-sdk/server/src/ai/agent.d.ts +33 -0
- package/dist-sdk/server/src/ai/agent.js +64 -13
- package/dist-sdk/server/src/app/user-service-factory.js +3 -0
- package/dist-sdk/server/src/app.controller.d.ts +7 -1
- package/dist-sdk/server/src/app.controller.js +55 -0
- package/dist-sdk/server/src/app.service.d.ts +114 -2
- package/dist-sdk/server/src/app.service.js +181 -4
- package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
- package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
- package/dist-sdk/server/src/data/data-registry.js +61 -0
- package/dist-sdk/server/src/data/data.types.d.ts +158 -0
- package/dist-sdk/server/src/data/data.types.js +24 -0
- package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
- package/dist-sdk/server/src/data/query-validation.js +245 -0
- package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
- package/dist-sdk/server/src/documents/document-conversion.js +341 -0
- package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
- package/dist-sdk/server/src/documents/library/chunking.js +263 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
- package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
- package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
- package/dist-sdk/server/src/documents/library/document.types.js +20 -0
- package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
- package/dist-sdk/server/src/documents/library/embedding.js +151 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
- package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
- package/dist-sdk/server/src/room/artifact.d.ts +8 -0
- package/dist-sdk/server/src/room/room.d.ts +7 -5
- package/dist-sdk/server/src/room/room.js +44 -7
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
- package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
- package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
- package/dist-sdk/server/src/sdk/index.d.ts +16 -2
- package/dist-sdk/server/src/sdk/index.js +37 -1
- package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
- package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
- package/dist-sdk/server/src/tools/core/index.js +3 -1
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
- package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
- package/dist-sdk/shared/types/app.types.d.ts +39 -5
- package/package.json +172 -167
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.queryDataTool = exports.describeDataTool = void 0;
|
|
4
|
+
const coerce_1 = require("../shared/coerce");
|
|
5
|
+
const data_registry_1 = require("../../data/data-registry");
|
|
6
|
+
const query_validation_1 = require("../../data/query-validation");
|
|
7
|
+
/** Serialized characters a query result may occupy. Under the tool's own budget. */
|
|
8
|
+
const RESULT_BUDGET = 20_000;
|
|
9
|
+
const QUERY_EXAMPLE = '{"dataset": "claims", "filters": [{"field": "year", "op": "gte", "value": 2022}], ' +
|
|
10
|
+
'"groupBy": ["customer"], "metrics": [{"fn": "sum", "field": "incurred"}], ' +
|
|
11
|
+
'"orderBy": [{"by": "sum_incurred", "dir": "desc"}], "limit": 10}';
|
|
12
|
+
const LIST_EXAMPLE = '{"dataset": "drivers", "filters": [{"field": "age", "op": "lt", "value": 30}, ' +
|
|
13
|
+
'{"field": "active", "op": "eq", "value": true}], "select": ["firstName", "lastName", "age"]}';
|
|
14
|
+
/** Names every dataset, for an error that teaches rather than just refuses. */
|
|
15
|
+
function datasetNames() {
|
|
16
|
+
return (0, data_registry_1.listDatasets)().map((set) => set.name);
|
|
17
|
+
}
|
|
18
|
+
exports.describeDataTool = {
|
|
19
|
+
name: 'describe_data',
|
|
20
|
+
description: 'Lists the datasets you can query, or the fields of one dataset. Your attached ' +
|
|
21
|
+
'data guide already describes these — use this when you need to confirm a field ' +
|
|
22
|
+
'exists, or when the guide and a query result disagree.',
|
|
23
|
+
parameters: [
|
|
24
|
+
{
|
|
25
|
+
name: 'dataset',
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'The dataset to describe. Omit to list every dataset.',
|
|
28
|
+
required: false,
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
handler: async (args) => {
|
|
32
|
+
if (!(0, data_registry_1.hasDataSources)()) {
|
|
33
|
+
return {
|
|
34
|
+
ok: false,
|
|
35
|
+
summary: 'No data is available to query',
|
|
36
|
+
error: 'This application has not made any data available to query.',
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const wanted = args.dataset === undefined || args.dataset === null || args.dataset === ''
|
|
40
|
+
? ''
|
|
41
|
+
: (0, coerce_1.str)(args.dataset, 'dataset');
|
|
42
|
+
if (!wanted) {
|
|
43
|
+
const sets = (0, data_registry_1.listDatasets)();
|
|
44
|
+
return {
|
|
45
|
+
ok: true,
|
|
46
|
+
summary: `Listed ${sets.length} dataset(s)`,
|
|
47
|
+
datasets: sets.map((set) => ({
|
|
48
|
+
name: set.name,
|
|
49
|
+
label: set.label || set.name,
|
|
50
|
+
description: set.description,
|
|
51
|
+
})),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const set = (0, data_registry_1.listDatasets)().find((candidate) => candidate.name === wanted);
|
|
55
|
+
if (!set) {
|
|
56
|
+
return {
|
|
57
|
+
ok: false,
|
|
58
|
+
summary: `No dataset called "${wanted}"`,
|
|
59
|
+
error: `Unknown dataset "${wanted}". Available datasets:`,
|
|
60
|
+
available: datasetNames(),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
ok: true,
|
|
65
|
+
summary: `Described the "${set.name}" dataset`,
|
|
66
|
+
dataset: set.name,
|
|
67
|
+
label: set.label || set.name,
|
|
68
|
+
description: set.description,
|
|
69
|
+
notes: set.notes || [],
|
|
70
|
+
fields: set.fields,
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
timeoutMs: 5_000,
|
|
74
|
+
};
|
|
75
|
+
exports.queryDataTool = {
|
|
76
|
+
name: 'query_data',
|
|
77
|
+
description: 'Answers a question about the application\'s data. Pass a JSON query naming a ' +
|
|
78
|
+
'dataset from your data guide, with optional filters, groupBy, metrics, orderBy ' +
|
|
79
|
+
'and limit. Aggregate example: ' +
|
|
80
|
+
QUERY_EXAMPLE +
|
|
81
|
+
' — listing example: ' +
|
|
82
|
+
LIST_EXAMPLE +
|
|
83
|
+
' Only the datasets and fields in your data guide exist; if a question needs ' +
|
|
84
|
+
'something that is not there, say so rather than substituting a field that looks close.',
|
|
85
|
+
parameters: [
|
|
86
|
+
{
|
|
87
|
+
name: 'query',
|
|
88
|
+
type: 'string',
|
|
89
|
+
description: 'The query as a JSON object. Example: ' + QUERY_EXAMPLE,
|
|
90
|
+
required: true,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
handler: async (args, _helpers, context) => {
|
|
94
|
+
if (!(0, data_registry_1.hasDataSources)()) {
|
|
95
|
+
return {
|
|
96
|
+
ok: false,
|
|
97
|
+
summary: 'No data is available to query',
|
|
98
|
+
error: 'This application has not made any data available to query.',
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const raw = (0, coerce_1.jsonObject)(args.query, 'query', QUERY_EXAMPLE);
|
|
102
|
+
const checked = (0, query_validation_1.validateQuery)(raw, (0, data_registry_1.listDatasets)());
|
|
103
|
+
if (!checked.ok) {
|
|
104
|
+
// A refusal, not a malfunction: it names what was allowed instead so
|
|
105
|
+
// the next turn can be right rather than another guess.
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
summary: 'Query refused',
|
|
109
|
+
error: checked.error,
|
|
110
|
+
...(checked.available ? { available: checked.available } : {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const source = (0, data_registry_1.sourceForDataset)(checked.query.dataset);
|
|
114
|
+
if (!source) {
|
|
115
|
+
return {
|
|
116
|
+
ok: false,
|
|
117
|
+
summary: `No source offers "${checked.query.dataset}"`,
|
|
118
|
+
error: `Unknown dataset "${checked.query.dataset}". Available datasets:`,
|
|
119
|
+
available: datasetNames(),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const result = await source.execute(checked.query, context);
|
|
123
|
+
const rows = Array.isArray(result?.rows) ? result.rows : [];
|
|
124
|
+
const fitted = fitRows(rows);
|
|
125
|
+
return {
|
|
126
|
+
ok: true,
|
|
127
|
+
summary: summarize(checked.query.dataset, fitted.rows.length, result?.totalRows),
|
|
128
|
+
dataset: checked.query.dataset,
|
|
129
|
+
// Echoed so an answer can state the question it actually asked, and
|
|
130
|
+
// so a wrong answer can be traced to a wrong query.
|
|
131
|
+
query: checked.query,
|
|
132
|
+
rowCount: fitted.rows.length,
|
|
133
|
+
...(typeof result?.totalRows === 'number' ? { totalRows: result.totalRows } : {}),
|
|
134
|
+
...(fitted.dropped > 0
|
|
135
|
+
? {
|
|
136
|
+
truncated: true,
|
|
137
|
+
note: `${fitted.dropped} more row(s) were dropped to fit the result size. ` +
|
|
138
|
+
'Add filters, group the data, or lower the limit.',
|
|
139
|
+
}
|
|
140
|
+
: {}),
|
|
141
|
+
rows: fitted.rows,
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
// Rows are the payload, and a grouped answer is worth reading whole. Still
|
|
145
|
+
// modest: every result is appended to the calling agent's history.
|
|
146
|
+
maxResultChars: 24_000,
|
|
147
|
+
timeoutMs: 30_000,
|
|
148
|
+
};
|
|
149
|
+
/** Drops trailing rows until the payload fits, reporting how many went. */
|
|
150
|
+
function fitRows(rows) {
|
|
151
|
+
let kept = rows;
|
|
152
|
+
while (kept.length > 0 && JSON.stringify(kept).length > RESULT_BUDGET) {
|
|
153
|
+
kept = kept.slice(0, Math.max(1, Math.floor(kept.length / 2)));
|
|
154
|
+
if (kept.length === 1 && JSON.stringify(kept).length > RESULT_BUDGET) {
|
|
155
|
+
return { rows: [], dropped: rows.length };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { rows: kept, dropped: rows.length - kept.length };
|
|
159
|
+
}
|
|
160
|
+
function summarize(dataset, returned, total) {
|
|
161
|
+
if (typeof total === 'number' && total > returned) {
|
|
162
|
+
return `Queried ${dataset}: ${returned} of ${total} rows`;
|
|
163
|
+
}
|
|
164
|
+
return `Queried ${dataset}: ${returned} row(s)`;
|
|
165
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finding, reading and holding a host's documents.
|
|
3
|
+
*
|
|
4
|
+
* There are two ways for an agent to use a document, and they cost very
|
|
5
|
+
* different amounts. It can look things up — search for a passage, read the
|
|
6
|
+
* pages around it — which puts only what it read into its history. Or it can
|
|
7
|
+
* hold the whole document, which puts every page into every request it makes
|
|
8
|
+
* until it lets go. Looking up is right for "what does the contract say about
|
|
9
|
+
* termination". Holding is right for "review this contract" or "compare these
|
|
10
|
+
* two", where no amount of searching substitutes for having read the thing.
|
|
11
|
+
*
|
|
12
|
+
* So looking up is the default and cheap, and holding is an explicit step with
|
|
13
|
+
* a size check in front of it: past a threshold the agent has to confirm it
|
|
14
|
+
* means to, and is told what it will cost; past a ceiling it cannot, and is told
|
|
15
|
+
* to read in pages instead.
|
|
16
|
+
*
|
|
17
|
+
* A document id from the agent is only ever used after it is found in what the
|
|
18
|
+
* host lists for this call's context — never passed through on trust.
|
|
19
|
+
*/
|
|
20
|
+
import { NativeToolDefinition } from '../native-tool.types';
|
|
21
|
+
/**
|
|
22
|
+
* The file name a held library document is attached under.
|
|
23
|
+
*
|
|
24
|
+
* It carries the document id so a held document can be found again, released,
|
|
25
|
+
* and told apart from the documents an agent's own configuration attached — a
|
|
26
|
+
* host resetting a conversation releases these and keeps those.
|
|
27
|
+
*/
|
|
28
|
+
export declare function libraryAttachmentName(documentId: string, name: string): string;
|
|
29
|
+
/** Whether an attachment is a library document an agent chose to hold. */
|
|
30
|
+
export declare function isLibraryAttachment(fileName: string): boolean;
|
|
31
|
+
/** The library document id an attachment holds, or undefined for any other attachment. */
|
|
32
|
+
export declare function libraryDocumentIdOf(fileName: string): string | undefined;
|
|
33
|
+
export declare const listDocumentsTool: NativeToolDefinition;
|
|
34
|
+
export declare const findInDocumentsTool: NativeToolDefinition;
|
|
35
|
+
export declare const readDocumentTool: NativeToolDefinition;
|
|
36
|
+
export declare const loadDocumentTool: NativeToolDefinition;
|
|
37
|
+
export declare const unloadDocumentTool: NativeToolDefinition;
|
|
38
|
+
/** Every document tool, in the order an agent would reach for them. */
|
|
39
|
+
export declare const documentTools: NativeToolDefinition[];
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.documentTools = exports.unloadDocumentTool = exports.loadDocumentTool = exports.readDocumentTool = exports.findInDocumentsTool = exports.listDocumentsTool = void 0;
|
|
4
|
+
exports.libraryAttachmentName = libraryAttachmentName;
|
|
5
|
+
exports.isLibraryAttachment = isLibraryAttachment;
|
|
6
|
+
exports.libraryDocumentIdOf = libraryDocumentIdOf;
|
|
7
|
+
const coerce_1 = require("../shared/coerce");
|
|
8
|
+
const document_registry_1 = require("../../documents/library/document-registry");
|
|
9
|
+
/** A holding request past this many characters must be confirmed. Override with `DOCUMENT_LOAD_CONFIRM_CHARS`. */
|
|
10
|
+
const DEFAULT_LOAD_CONFIRM_CHARS = 60_000;
|
|
11
|
+
/** Library documents one agent may hold in total. Override with `DOCUMENT_LOAD_MAX_CHARS`. */
|
|
12
|
+
const DEFAULT_LOAD_MAX_CHARS = 400_000;
|
|
13
|
+
/** A page of `read_document` output. Leaves room under the tool budget for the envelope. */
|
|
14
|
+
const READ_PART_CHARS = 20_000;
|
|
15
|
+
/** Serialized characters of search hits, under the tool's own budget. */
|
|
16
|
+
const SEARCH_BUDGET = 14_000;
|
|
17
|
+
/** One excerpt's ceiling, so a single long passage cannot crowd out the rest. */
|
|
18
|
+
const EXCERPT_CHARS = 1_500;
|
|
19
|
+
const DEFAULT_HITS = 8;
|
|
20
|
+
const MAX_HITS = 20;
|
|
21
|
+
/** Rough characters per token, for telling an agent what holding a document costs. */
|
|
22
|
+
const CHARS_PER_TOKEN = 4;
|
|
23
|
+
const LIBRARY_MARKER = /\s\[library ([^\]]+)\]\.md$/;
|
|
24
|
+
/**
|
|
25
|
+
* The file name a held library document is attached under.
|
|
26
|
+
*
|
|
27
|
+
* It carries the document id so a held document can be found again, released,
|
|
28
|
+
* and told apart from the documents an agent's own configuration attached — a
|
|
29
|
+
* host resetting a conversation releases these and keeps those.
|
|
30
|
+
*/
|
|
31
|
+
function libraryAttachmentName(documentId, name) {
|
|
32
|
+
const safe = (name || 'Document').replace(/[\\/:*?"<>|\[\]]/g, '_').slice(0, 120);
|
|
33
|
+
return `${safe} [library ${documentId}].md`;
|
|
34
|
+
}
|
|
35
|
+
/** Whether an attachment is a library document an agent chose to hold. */
|
|
36
|
+
function isLibraryAttachment(fileName) {
|
|
37
|
+
return LIBRARY_MARKER.test(fileName || '');
|
|
38
|
+
}
|
|
39
|
+
/** The library document id an attachment holds, or undefined for any other attachment. */
|
|
40
|
+
function libraryDocumentIdOf(fileName) {
|
|
41
|
+
return (fileName || '').match(LIBRARY_MARKER)?.[1];
|
|
42
|
+
}
|
|
43
|
+
function limitFromEnv(name, fallback) {
|
|
44
|
+
const value = Number(process.env[name]);
|
|
45
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
46
|
+
}
|
|
47
|
+
const unavailable = {
|
|
48
|
+
ok: false,
|
|
49
|
+
summary: 'No documents are available',
|
|
50
|
+
error: 'This application has not made any documents available to search.',
|
|
51
|
+
};
|
|
52
|
+
/** Every document in scope, each paired with the source that owns it. */
|
|
53
|
+
async function inScope(context) {
|
|
54
|
+
const listed = await Promise.all((0, document_registry_1.listDocumentSources)().map(async (source) => ((await source.list(context)) || []).map((document) => ({ source, document }))));
|
|
55
|
+
return listed.flat();
|
|
56
|
+
}
|
|
57
|
+
/** How an agent is told which documents it could have named. */
|
|
58
|
+
function choices(scope) {
|
|
59
|
+
return scope.map(({ document }) => ({ documentId: document.documentId, name: document.name }));
|
|
60
|
+
}
|
|
61
|
+
function unknownDocument(documentId, scope) {
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
summary: `No document "${documentId}"`,
|
|
65
|
+
error: scope.length
|
|
66
|
+
? `There is no document "${documentId}" here. Use one of these documentIds:`
|
|
67
|
+
: 'There are no documents here yet. The user can add some.',
|
|
68
|
+
...(scope.length ? { available: choices(scope) } : {}),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** An optional string argument: absent, null and empty all mean "not given". */
|
|
72
|
+
function optionalString(value, param) {
|
|
73
|
+
return value === undefined || value === null || value === '' ? '' : (0, coerce_1.str)(value, param);
|
|
74
|
+
}
|
|
75
|
+
function clip(text, max) {
|
|
76
|
+
return text.length <= max ? text : `${text.slice(0, max).trimEnd()} …`;
|
|
77
|
+
}
|
|
78
|
+
exports.listDocumentsTool = {
|
|
79
|
+
name: 'list_documents',
|
|
80
|
+
description: 'Lists the documents available to you: each one\'s documentId, name, kind, page count, ' +
|
|
81
|
+
'size and a short summary, and which of them you are holding in full. Documents can ' +
|
|
82
|
+
'be added while you work, so list again rather than relying on an earlier answer.',
|
|
83
|
+
parameters: [],
|
|
84
|
+
handler: async (_args, helpers, context) => {
|
|
85
|
+
if (!(0, document_registry_1.hasDocumentSources)())
|
|
86
|
+
return unavailable;
|
|
87
|
+
const scope = await inScope(context);
|
|
88
|
+
const held = await heldLibraryIds(helpers);
|
|
89
|
+
return {
|
|
90
|
+
ok: true,
|
|
91
|
+
summary: `Listed ${scope.length} document(s)`,
|
|
92
|
+
documents: scope.map(({ document }) => ({
|
|
93
|
+
documentId: document.documentId,
|
|
94
|
+
name: document.name,
|
|
95
|
+
...(document.kind ? { kind: document.kind } : {}),
|
|
96
|
+
pages: document.pages,
|
|
97
|
+
chars: document.chars,
|
|
98
|
+
...(document.addedAt ? { addedAt: document.addedAt } : {}),
|
|
99
|
+
...(document.state && document.state !== 'ready' ? { state: document.state } : {}),
|
|
100
|
+
...(held.has(document.documentId) ? { heldInFull: true } : {}),
|
|
101
|
+
...(document.summary ? { summary: clip(document.summary, 600) } : {}),
|
|
102
|
+
})),
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
maxResultChars: 12_000,
|
|
106
|
+
timeoutMs: 15_000,
|
|
107
|
+
};
|
|
108
|
+
exports.findInDocumentsTool = {
|
|
109
|
+
name: 'find_in_documents',
|
|
110
|
+
description: 'Searches the documents for passages about something, and returns the best matches ' +
|
|
111
|
+
'with the document, page and section each came from. Search in the words the ' +
|
|
112
|
+
'documents would use. Pass a documentId to search just one. Use read_document to ' +
|
|
113
|
+
'see a whole page around a match. Cite the document and page whenever you use a passage.',
|
|
114
|
+
parameters: [
|
|
115
|
+
{ name: 'query', type: 'string', description: 'What to look for.', required: true },
|
|
116
|
+
{
|
|
117
|
+
name: 'documentId',
|
|
118
|
+
type: 'string',
|
|
119
|
+
description: 'Search only this document. Omit to search them all.',
|
|
120
|
+
required: false,
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
name: 'limit',
|
|
124
|
+
type: 'number',
|
|
125
|
+
description: `How many passages to return, up to ${MAX_HITS}. Defaults to ${DEFAULT_HITS}.`,
|
|
126
|
+
required: false,
|
|
127
|
+
},
|
|
128
|
+
],
|
|
129
|
+
handler: async (args, _helpers, context) => {
|
|
130
|
+
if (!(0, document_registry_1.hasDocumentSources)())
|
|
131
|
+
return unavailable;
|
|
132
|
+
const query = (0, coerce_1.str)(args.query, 'query');
|
|
133
|
+
if (!query) {
|
|
134
|
+
return { ok: false, summary: 'Nothing to search for', error: 'Say what to look for in "query".' };
|
|
135
|
+
}
|
|
136
|
+
const limit = Math.min(Math.max(1, (0, coerce_1.int)(args.limit, 'limit', DEFAULT_HITS)), MAX_HITS);
|
|
137
|
+
const scope = await inScope(context);
|
|
138
|
+
const wanted = optionalString(args.documentId, 'documentId');
|
|
139
|
+
let targets = scope;
|
|
140
|
+
if (wanted) {
|
|
141
|
+
targets = scope.filter(({ document }) => document.documentId === wanted);
|
|
142
|
+
if (!targets.length)
|
|
143
|
+
return unknownDocument(wanted, scope);
|
|
144
|
+
}
|
|
145
|
+
if (!targets.length) {
|
|
146
|
+
return { ok: true, summary: 'No documents to search', hits: [], note: 'There are no documents here yet.' };
|
|
147
|
+
}
|
|
148
|
+
// Group by source so each is asked only about its own documents.
|
|
149
|
+
const bySource = new Map();
|
|
150
|
+
for (const { source, document } of targets) {
|
|
151
|
+
bySource.set(source, [...(bySource.get(source) || []), document.documentId]);
|
|
152
|
+
}
|
|
153
|
+
// A source only ever knows its own documents, so the ids need passing only
|
|
154
|
+
// to narrow a search to the one the agent named.
|
|
155
|
+
const found = await Promise.all([...bySource].map(([source, documentIds]) => source.search(context, { query, limit, ...(wanted ? { documentIds } : {}) })));
|
|
156
|
+
const hits = found
|
|
157
|
+
.flat()
|
|
158
|
+
.sort((a, b) => b.score - a.score)
|
|
159
|
+
.slice(0, limit);
|
|
160
|
+
const notReady = targets.filter(({ document }) => document.state && document.state !== 'ready');
|
|
161
|
+
const shaped = fitHits(hits);
|
|
162
|
+
return {
|
|
163
|
+
ok: true,
|
|
164
|
+
summary: `Found ${shaped.length} passage(s) for "${clip(query, 60)}"`,
|
|
165
|
+
hits: shaped,
|
|
166
|
+
...(notReady.length
|
|
167
|
+
? {
|
|
168
|
+
note: 'These documents are not searchable yet and were not searched: ' +
|
|
169
|
+
notReady.map(({ document }) => `"${document.name}" (${document.state})`).join(', ') +
|
|
170
|
+
'. They can still be read with read_document.',
|
|
171
|
+
}
|
|
172
|
+
: shaped.length
|
|
173
|
+
? {}
|
|
174
|
+
: { note: 'Nothing matched. Try the words the document itself would use, or read_document.' }),
|
|
175
|
+
};
|
|
176
|
+
},
|
|
177
|
+
maxResultChars: 16_000,
|
|
178
|
+
timeoutMs: 30_000,
|
|
179
|
+
};
|
|
180
|
+
exports.readDocumentTool = {
|
|
181
|
+
name: 'read_document',
|
|
182
|
+
description: 'Reads pages of a document. Give fromPage and toPage for a range, or omit them to read ' +
|
|
183
|
+
'from the start. Long reads come back in parts — pass the nextPart you were given to ' +
|
|
184
|
+
'continue. Cite the page numbers you read from.',
|
|
185
|
+
parameters: [
|
|
186
|
+
{ name: 'documentId', type: 'string', description: 'The document to read.', required: true },
|
|
187
|
+
{ name: 'fromPage', type: 'number', description: 'First page. Defaults to 1.', required: false },
|
|
188
|
+
{ name: 'toPage', type: 'number', description: 'Last page. Defaults to the end.', required: false },
|
|
189
|
+
{ name: 'part', type: 'number', description: 'Which part of a long read. Defaults to 1.', required: false },
|
|
190
|
+
],
|
|
191
|
+
handler: async (args, _helpers, context) => {
|
|
192
|
+
if (!(0, document_registry_1.hasDocumentSources)())
|
|
193
|
+
return unavailable;
|
|
194
|
+
const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
|
|
195
|
+
const scope = await inScope(context);
|
|
196
|
+
const match = scope.find(({ document }) => document.documentId === documentId);
|
|
197
|
+
if (!match)
|
|
198
|
+
return unknownDocument(documentId, scope);
|
|
199
|
+
const pageCount = Math.max(1, match.document.pages || 1);
|
|
200
|
+
const requestedFrom = (0, coerce_1.int)(args.fromPage, 'fromPage', 1);
|
|
201
|
+
if (requestedFrom > pageCount) {
|
|
202
|
+
return {
|
|
203
|
+
ok: false,
|
|
204
|
+
summary: 'Page out of range',
|
|
205
|
+
error: `"${match.document.name}" has ${pageCount} page(s); fromPage must be 1 to ${pageCount}.`,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
const from = Math.max(1, requestedFrom);
|
|
209
|
+
const to = Math.min(Math.max(from, (0, coerce_1.int)(args.toPage, 'toPage', pageCount)), pageCount);
|
|
210
|
+
const read = await match.source.read(context, documentId, { from, to });
|
|
211
|
+
if (!read)
|
|
212
|
+
return unknownDocument(documentId, scope);
|
|
213
|
+
const text = read.pages
|
|
214
|
+
.map((page) => `--- Page ${page.pageNum}${page.label ? ` (${page.label})` : ''} ---\n${page.markdown}`)
|
|
215
|
+
.join('\n\n');
|
|
216
|
+
const parts = Math.max(1, Math.ceil(text.length / READ_PART_CHARS));
|
|
217
|
+
const part = Math.min(Math.max(1, (0, coerce_1.int)(args.part, 'part', 1)), parts);
|
|
218
|
+
const body = text.slice((part - 1) * READ_PART_CHARS, part * READ_PART_CHARS);
|
|
219
|
+
return {
|
|
220
|
+
ok: true,
|
|
221
|
+
summary: `Read "${read.name}" pages ${from}–${to}${parts > 1 ? `, part ${part} of ${parts}` : ''}`,
|
|
222
|
+
documentId,
|
|
223
|
+
name: read.name,
|
|
224
|
+
pageCount: read.pageCount,
|
|
225
|
+
fromPage: from,
|
|
226
|
+
toPage: to,
|
|
227
|
+
...(parts > 1 ? { part, parts, ...(part < parts ? { nextPart: part + 1 } : {}) } : {}),
|
|
228
|
+
text: body,
|
|
229
|
+
};
|
|
230
|
+
},
|
|
231
|
+
maxResultChars: 24_000,
|
|
232
|
+
timeoutMs: 15_000,
|
|
233
|
+
};
|
|
234
|
+
exports.loadDocumentTool = {
|
|
235
|
+
name: 'load_document',
|
|
236
|
+
description: 'Holds a whole document in your context, so you can work across all of it at once. ' +
|
|
237
|
+
'Use it only when the task needs the entire document — a full review, a summary of ' +
|
|
238
|
+
'everything, or a comparison of two documents. To answer a question about part of a ' +
|
|
239
|
+
'document, use find_in_documents and read_document instead: a held document is sent ' +
|
|
240
|
+
'with every request you make until you unload it. Large documents need confirm: true, ' +
|
|
241
|
+
'and you will be told the size first.',
|
|
242
|
+
parameters: [
|
|
243
|
+
{ name: 'documentId', type: 'string', description: 'The document to hold.', required: true },
|
|
244
|
+
{
|
|
245
|
+
name: 'confirm',
|
|
246
|
+
type: 'boolean',
|
|
247
|
+
description: 'Set true to hold a large document after being told its size.',
|
|
248
|
+
required: false,
|
|
249
|
+
},
|
|
250
|
+
],
|
|
251
|
+
handler: async (args, helpers, context) => {
|
|
252
|
+
if (!(0, document_registry_1.hasDocumentSources)())
|
|
253
|
+
return unavailable;
|
|
254
|
+
if (!helpers.documents) {
|
|
255
|
+
return {
|
|
256
|
+
ok: false,
|
|
257
|
+
summary: 'Cannot hold documents here',
|
|
258
|
+
error: 'Holding a document needs a calling agent. Use read_document instead.',
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
|
|
262
|
+
const scope = await inScope(context);
|
|
263
|
+
const match = scope.find(({ document }) => document.documentId === documentId);
|
|
264
|
+
if (!match)
|
|
265
|
+
return unknownDocument(documentId, scope);
|
|
266
|
+
const held = await helpers.documents.held();
|
|
267
|
+
if (held.some((file) => libraryDocumentIdOf(file.fileName) === documentId)) {
|
|
268
|
+
return {
|
|
269
|
+
ok: true,
|
|
270
|
+
summary: `Already holding "${match.document.name}"`,
|
|
271
|
+
note: 'It is already in your context. Work from it directly.',
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
const confirmAbove = limitFromEnv('DOCUMENT_LOAD_CONFIRM_CHARS', DEFAULT_LOAD_CONFIRM_CHARS);
|
|
275
|
+
const ceiling = limitFromEnv('DOCUMENT_LOAD_MAX_CHARS', DEFAULT_LOAD_MAX_CHARS);
|
|
276
|
+
const heldLibrary = held.filter((file) => isLibraryAttachment(file.fileName));
|
|
277
|
+
const alreadyHeld = heldLibrary.reduce((sum, file) => sum + file.chars, 0);
|
|
278
|
+
const size = match.document.chars;
|
|
279
|
+
if (alreadyHeld + size > ceiling) {
|
|
280
|
+
return {
|
|
281
|
+
ok: false,
|
|
282
|
+
summary: `"${match.document.name}" is too large to hold`,
|
|
283
|
+
error: `Holding it would put ${Math.round((alreadyHeld + size) / 1000)}k characters of documents in your ` +
|
|
284
|
+
`context; the limit is ${Math.round(ceiling / 1000)}k. ` +
|
|
285
|
+
(heldLibrary.length
|
|
286
|
+
? 'Unload a document you have finished with, or read this one in pages with read_document.'
|
|
287
|
+
: 'Read it in pages with read_document, and use find_in_documents to locate what matters.'),
|
|
288
|
+
...(heldLibrary.length ? { holding: heldLibrary.map(describeHeld) } : {}),
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
if (size > confirmAbove && !(0, coerce_1.bool)(args.confirm)) {
|
|
292
|
+
return {
|
|
293
|
+
ok: false,
|
|
294
|
+
summary: `Holding "${match.document.name}" needs confirmation`,
|
|
295
|
+
error: `"${match.document.name}" is about ${Math.round(size / CHARS_PER_TOKEN / 1000)}k tokens ` +
|
|
296
|
+
`(${match.document.pages} page(s)). Holding it adds that to every request you make until you ` +
|
|
297
|
+
'unload it. If the task needs the whole document, call load_document again with confirm: true. ' +
|
|
298
|
+
'If it needs part of it, use find_in_documents or read_document.',
|
|
299
|
+
chars: size,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
const text = await match.source.fullText(context, documentId);
|
|
303
|
+
if (!text)
|
|
304
|
+
return unknownDocument(documentId, scope);
|
|
305
|
+
await helpers.documents.attach(libraryAttachmentName(documentId, text.name), `# ${text.name}\n\n${text.markdown}`);
|
|
306
|
+
return {
|
|
307
|
+
ok: true,
|
|
308
|
+
summary: `Holding "${text.name}" in full`,
|
|
309
|
+
note: 'The whole document is in your context from your next step. Unload it with ' +
|
|
310
|
+
'unload_document when the work that needed it is done.',
|
|
311
|
+
holding: [...heldLibrary.map(describeHeld), { documentId, name: text.name, chars: text.markdown.length }],
|
|
312
|
+
};
|
|
313
|
+
},
|
|
314
|
+
timeoutMs: 30_000,
|
|
315
|
+
};
|
|
316
|
+
exports.unloadDocumentTool = {
|
|
317
|
+
name: 'unload_document',
|
|
318
|
+
description: 'Stops holding a document you loaded with load_document, so it is no longer sent with ' +
|
|
319
|
+
'every request. You can still search and read it afterwards.',
|
|
320
|
+
parameters: [{ name: 'documentId', type: 'string', description: 'The document to let go of.', required: true }],
|
|
321
|
+
handler: async (args, helpers) => {
|
|
322
|
+
if (!helpers.documents) {
|
|
323
|
+
return { ok: false, summary: 'Cannot hold documents here', error: 'There is nothing held to unload.' };
|
|
324
|
+
}
|
|
325
|
+
const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
|
|
326
|
+
const held = (await helpers.documents.held()).filter((file) => isLibraryAttachment(file.fileName));
|
|
327
|
+
const match = held.find((file) => libraryDocumentIdOf(file.fileName) === documentId);
|
|
328
|
+
if (!match) {
|
|
329
|
+
return {
|
|
330
|
+
ok: false,
|
|
331
|
+
summary: `Not holding "${documentId}"`,
|
|
332
|
+
error: held.length
|
|
333
|
+
? 'You are not holding that document. You are holding:'
|
|
334
|
+
: 'You are not holding any documents.',
|
|
335
|
+
...(held.length ? { holding: held.map(describeHeld) } : {}),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
await helpers.documents.detach(match.documentId);
|
|
339
|
+
const name = match.fileName.replace(LIBRARY_MARKER, '');
|
|
340
|
+
return {
|
|
341
|
+
ok: true,
|
|
342
|
+
summary: `Stopped holding "${name}"`,
|
|
343
|
+
holding: held.filter((file) => file !== match).map(describeHeld),
|
|
344
|
+
};
|
|
345
|
+
},
|
|
346
|
+
timeoutMs: 15_000,
|
|
347
|
+
};
|
|
348
|
+
/** Every document tool, in the order an agent would reach for them. */
|
|
349
|
+
exports.documentTools = [
|
|
350
|
+
exports.listDocumentsTool,
|
|
351
|
+
exports.findInDocumentsTool,
|
|
352
|
+
exports.readDocumentTool,
|
|
353
|
+
exports.loadDocumentTool,
|
|
354
|
+
exports.unloadDocumentTool,
|
|
355
|
+
];
|
|
356
|
+
async function heldLibraryIds(helpers) {
|
|
357
|
+
if (!helpers.documents)
|
|
358
|
+
return new Set();
|
|
359
|
+
const held = await helpers.documents.held();
|
|
360
|
+
return new Set(held.map((file) => libraryDocumentIdOf(file.fileName)).filter(Boolean));
|
|
361
|
+
}
|
|
362
|
+
function describeHeld(file) {
|
|
363
|
+
return {
|
|
364
|
+
documentId: libraryDocumentIdOf(file.fileName),
|
|
365
|
+
name: file.fileName.replace(LIBRARY_MARKER, ''),
|
|
366
|
+
chars: file.chars,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
/** Trims excerpts until the hits fit, keeping every hit's citation whole. */
|
|
370
|
+
function fitHits(hits) {
|
|
371
|
+
let excerptChars = EXCERPT_CHARS;
|
|
372
|
+
let shaped = shape(hits, excerptChars);
|
|
373
|
+
while (JSON.stringify(shaped).length > SEARCH_BUDGET && excerptChars > 200) {
|
|
374
|
+
excerptChars = Math.floor(excerptChars * 0.75);
|
|
375
|
+
shaped = shape(hits, excerptChars);
|
|
376
|
+
}
|
|
377
|
+
while (shaped.length > 1 && JSON.stringify(shaped).length > SEARCH_BUDGET) {
|
|
378
|
+
shaped = shaped.slice(0, -1);
|
|
379
|
+
}
|
|
380
|
+
return shaped;
|
|
381
|
+
}
|
|
382
|
+
function shape(hits, excerptChars) {
|
|
383
|
+
return hits.map((hit) => ({
|
|
384
|
+
documentId: hit.documentId,
|
|
385
|
+
document: hit.name,
|
|
386
|
+
page: hit.pageNum,
|
|
387
|
+
...(hit.heading ? { section: hit.heading } : {}),
|
|
388
|
+
excerpt: clip(hit.excerpt || '', excerptChars),
|
|
389
|
+
score: Math.round(hit.score * 1000) / 1000,
|
|
390
|
+
}));
|
|
391
|
+
}
|
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.CORE_TOOL_GROUP = void 0;
|
|
18
18
|
exports.coreTools = coreTools;
|
|
19
|
+
const data_tools_1 = require("./data.tools");
|
|
20
|
+
const document_tools_1 = require("./document.tools");
|
|
19
21
|
const illustrate_tool_1 = require("./illustrate.tool");
|
|
20
22
|
const rename_tool_1 = require("./rename.tool");
|
|
21
23
|
/** The name the UI groups these under, in place of a pack name. */
|
|
@@ -28,5 +30,5 @@ exports.CORE_TOOL_GROUP = 'core';
|
|
|
28
30
|
* @returns The tool definitions
|
|
29
31
|
*/
|
|
30
32
|
function coreTools() {
|
|
31
|
-
return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool];
|
|
33
|
+
return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool, data_tools_1.describeDataTool, data_tools_1.queryDataTool, ...document_tools_1.documentTools];
|
|
32
34
|
}
|
|
@@ -254,6 +254,38 @@ export interface ToolIllustration {
|
|
|
254
254
|
*/
|
|
255
255
|
portrait(characterName: string, profile: string): PortraitTicket;
|
|
256
256
|
}
|
|
257
|
+
/** A document held in an agent's context. */
|
|
258
|
+
export interface ToolHeldDocument {
|
|
259
|
+
/** The attachment's id — what {@link ToolAgentDocuments.detach} takes. */
|
|
260
|
+
documentId: string;
|
|
261
|
+
fileName: string;
|
|
262
|
+
/** Its size in characters (bytes, for a binary file). */
|
|
263
|
+
chars: number;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The documents held in the calling agent's context — the ones prepended to
|
|
267
|
+
* every request it makes.
|
|
268
|
+
*
|
|
269
|
+
* Scoped to the caller by Briyah, from the room's own record of who is calling,
|
|
270
|
+
* so a tool can hold documents for the agent that asked and for no other.
|
|
271
|
+
*
|
|
272
|
+
* Holding a document is the expensive way to use it: it rides every one of the
|
|
273
|
+
* agent's subsequent requests until it is detached. It is the right way when the
|
|
274
|
+
* work needs the whole document at once — a full review, a comparison of two —
|
|
275
|
+
* and the wrong way to look one thing up.
|
|
276
|
+
*/
|
|
277
|
+
export interface ToolAgentDocuments {
|
|
278
|
+
/**
|
|
279
|
+
* Attaches text to the calling agent's context. A document already held under
|
|
280
|
+
* the same file name is replaced rather than duplicated.
|
|
281
|
+
* @returns The new attachment's id
|
|
282
|
+
*/
|
|
283
|
+
attach(fileName: string, body: string): Promise<string>;
|
|
284
|
+
/** Detaches one of the calling agent's documents. @returns Whether it was held */
|
|
285
|
+
detach(documentId: string): Promise<boolean>;
|
|
286
|
+
/** Everything the calling agent holds, including documents its configuration attached. */
|
|
287
|
+
held(): Promise<ToolHeldDocument[]>;
|
|
288
|
+
}
|
|
257
289
|
export interface ToolHelpers {
|
|
258
290
|
fetch: typeof fetch;
|
|
259
291
|
/**
|
|
@@ -273,6 +305,11 @@ export interface ToolHelpers {
|
|
|
273
305
|
* rather than dereferencing it.
|
|
274
306
|
*/
|
|
275
307
|
illustration?: ToolIllustration;
|
|
308
|
+
/**
|
|
309
|
+
* The documents held in the calling agent's context. Absent when there is no
|
|
310
|
+
* calling agent — the tool-test endpoint — or the host wired no store.
|
|
311
|
+
*/
|
|
312
|
+
documents?: ToolAgentDocuments;
|
|
276
313
|
}
|
|
277
314
|
/**
|
|
278
315
|
* An opaque, per-invocation value supplied by the host when it starts an
|