@drdoc-com/pi-drdoc 1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # Pi Plugin for Dr.DOC
2
+
3
+ An integration plugin Package for the **Pi Agent** (`pi.dev`) ecosystem to interact seamlessly with the [**Dr.DOC Document Management System** \(DMS/ECM\)](drdoc.com/node/de/products/web).
4
+
5
+ This plugin allows the Pi Agent to query Dr.DOC archives, fetch document blobs, store files locally, generate direct web links, and display inline document previews.
6
+
7
+ ---
8
+
9
+ ## System Architecture & Integration Directions
10
+
11
+ The integration between Pi Agent and Dr.DOC is split into two primary operational directions:
12
+
13
+ ### 1. Pi → Dr.DOC (This Plugin)
14
+ This plugin enables the **Pi Agent** to make outgoing API calls to **Dr.DOC**. The agent uses these tool functions to search archives, retrieve documents, save them locally, and process binary/image data.
15
+
16
+ ### 2. Dr.DOC → Pi (OpenAI API Wrapper)
17
+ To allow **Dr.DOC** (or external tools) to send requests to Pi using the standard OpenAI API format, the `@drdoc-com/pi-openai-api-wrapper` package can be used.
18
+
19
+ * **GitHub Repository:** [github.com/drdoc-com/pi-openai-api-wrapper](https://github.com/drdoc-com/pi-openai-api-wrapper)
20
+ * **Pi Package Registry:** [pi.dev/packages/@drdoc-com/pi-openai-api-wrapper](https://pi.dev/packages/@drdoc-com/pi-openai-api-wrapper)
21
+ * **npm Package:** [npmjs.com/package/@drdoc-com/pi-openai-api-wrapper](https://www.npmjs.com/package/@drdoc-com/pi-openai-api-wrapper)
22
+
23
+ ---
24
+
25
+ ## Features
26
+
27
+ * **Document Retrieval:** Fetches document blobs and metadata from Dr.DOC using archive names and record IDs.
28
+ * **Safe Local Storage:** Automatically saves retrieved files to a reliable user directory (`~/.drdoc/downloads/`), avoiding conflicts with host extension directories.
29
+ * **Inline Image Previews:** Generates Base64 data URLs for image files (`image/*`), enabling direct rendering in the Pi Agent interface.
30
+ * **Direct Web URL Generation:** Creates browser-accessible URLs for fetched documents (`https://drdoc.com/model/document?action=get&...`).
31
+ * **Robust Error Handling:** Checks HTTP status codes (`response.ok`) and handles binary buffers cleanly.
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ Install the package via npm or directly into your Pi extension environment:
38
+ ```bash
39
+ pi install npm:@drdoc-com/pi-drdoc
40
+ ```
41
+
42
+ Or via GitHub:
43
+ ```bash
44
+ pi install git:https://github.com/drdoc-com/pi-drdoc
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Configuration
50
+
51
+ The plugin utilizes configuration options supplied by the Dr.DOC client or environment variables.
52
+
53
+ ### Environment Variables
54
+
55
+ | Variable | Description | Default |
56
+ | --- | --- | --- |
57
+ | `DRDOC_BASE_URL` | Base URL of the Dr.DOC instance | `https://drdoc.com` |
58
+ | `DRDOC_CONFIG_DIR` (alt. `PI_CONFIG_DIR`) | Custom directory for config files | `~/.pi/agent` |
59
+ | `DRDOC_DOWNLOAD_DIR` | Custom directory for downloaded files | `~/.drdoc/downloads` |
60
+ | `DRDOC_IGNORE_SSL` | Ignore TLS/SSL Errors (Set `NODE_TLS_REJECT_UNAUTHORIZED=0`) | `` |
61
+ | `DRDOC_DEBUG` | Enable Debugging | `` |
62
+
63
+ ---
64
+
65
+ ## License
66
+
67
+ This project is licensed under the Apache License 2.0.
68
+ Dr.DOC DMS is licensed is under proprietary License.
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@drdoc-com/pi-drdoc",
3
+ "version": "1.0.0",
4
+ "description": "Dr.DOC DMS Integration Package for PI Agent",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": ["pi-package", "pi-agent", "drdoc", "rest-api", "skill", "dms", "Dr.DOC"],
8
+ "private": false,
9
+ "pi": {
10
+ "extensions": [
11
+ "./src/index.ts"
12
+ ]
13
+ },
14
+ "main": "dist/index.js",
15
+ "types": "dist/index.d.ts",
16
+ "scripts": {
17
+ "build": "tsc"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/drdoc-com/pi-drdoc.git"
22
+ },
23
+ "author": "Dr.DOC GmbH, DE-80802 Munich",
24
+ "devDependencies": {
25
+ "typescript": "^7.0.2",
26
+ "@types/node": "^26.2.0"
27
+ },
28
+ "peerDependencies": {
29
+ "@earendil-works/pi-coding-agent": "*"
30
+ }
31
+ }
32
+
@@ -0,0 +1,468 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import * as os from "os";
4
+
5
+ import { URLSearchParams } from "url";
6
+
7
+ /**
8
+ * Interface für Standard-Antworten der Dr.DOC REST API
9
+ */
10
+ export interface DrDocResponse<T = any> {
11
+ HasError: boolean;
12
+ Error?: {
13
+ Message: string;
14
+ InternalMessage?: string;
15
+ };
16
+ Count?: number;
17
+ CountTotal?: number;
18
+ Result?: T;
19
+ $ModelType?: string;
20
+ }
21
+
22
+ /**
23
+ * Konfiguration für den DrDOC Client
24
+ */
25
+ export interface DrDocConfig {
26
+ baseUrl: string;
27
+ username?: string;
28
+ password?: string;
29
+ totp?: string;
30
+ /**
31
+ * Deaktiviert die Zertifikatsprüfung für selbstsignierte HTTPS-Zertifikate.
32
+ */
33
+ ignoreSSL?: boolean;
34
+ sessionCookie?: string;
35
+ authHeader?: string;
36
+ }
37
+
38
+ /**
39
+ * Hilfsmethode zum sicheren Abrufen des UI-Objekts aus dem globalen Kontext (globalThis).
40
+ * Verhindert ReferenceError-Ausnahmen bei nicht deklarierten Variablen.
41
+ */
42
+ function getGlobalUI(): any {
43
+ const g = globalThis as any;
44
+ return g.ctx?.ui || g.pi?.ui;
45
+ }
46
+
47
+ export function msgLog(...args: any[]) {
48
+ console.log(...args);
49
+ const ui = getGlobalUI();
50
+ if (typeof ui?.notify === "function") {
51
+ ui.notify(...args);
52
+ }
53
+ }
54
+
55
+ export function msgInfo(message: string) {
56
+ const ui = getGlobalUI();
57
+ if (typeof ui?.notify === "function") {
58
+ ui.notify(message, "info");
59
+ } else {
60
+ console.log(message);
61
+ }
62
+ }
63
+
64
+ export function msgError(message: string) {
65
+ const ui = getGlobalUI();
66
+ if (typeof ui?.notify === "function") {
67
+ ui.notify(message, "error");
68
+ } else {
69
+ console.error(message);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Liefert den absoluten Pfad zum globalen Einstellungs-Verzeichnis (~/.pi/agent/).
75
+ */
76
+ export function getGlobalSettingsDir(): string {
77
+ // Berücksichtigung von benutzerdefinierten Pfaden über Umgebungsvariablen
78
+ if (process.env.DRDOC_CONFIG_DIR) {
79
+ return process.env.DRDOC_CONFIG_DIR;
80
+ }
81
+ if (process.env.PI_CONFIG_DIR) {
82
+ return process.env.PI_CONFIG_DIR;
83
+ }
84
+ return path.join(os.homedir(), ".pi", "agent");
85
+ // path.resolve(process.cwd()
86
+ }
87
+
88
+ /**
89
+ * Client-Klasse für die Interaktion mit der Dr.DOC REST API.
90
+ * Verwaltet Sitzungscookies und führt HTTP-Requests aus.
91
+ */
92
+ export class DrDocClient {
93
+ private config: DrDocConfig;
94
+ private storageFilePath: string;
95
+ //private sessionCookie: string | null = null;
96
+ //private authHeader: string | null = null;
97
+
98
+ constructor(config: DrDocConfig) {
99
+ this.config = config; //{ ...config };
100
+ this.storageFilePath = path.join(getGlobalSettingsDir(), ".drdoc-session.json");
101
+
102
+ // Vorhandene Anmeldedaten beim Instanziieren aus der JSON-Datei laden
103
+ this.loadCredentials();
104
+
105
+ // Basis-Konfiguration und HTTP-Einstellungen anwenden
106
+ this.applyConfig();
107
+
108
+ if (process.env.DRDOC_DEBUG)
109
+ msgLog('Ctor', this.config);
110
+ }
111
+
112
+ public getConfig(): any {
113
+ return this.config;
114
+ }
115
+
116
+ /**
117
+ * Wendet die Eigenschaften aus 'config' auf die Instanzvariablen an.
118
+ */
119
+ private applyConfig(): void {
120
+ if (!this.config.baseUrl) {
121
+ this.config.baseUrl = process.env.DRDOC_BASE_URL;
122
+ }
123
+ if (!this.config.baseUrl) {
124
+ throw new Error("DrDocClient erfordert eine gültige 'baseUrl' in der Konfiguration.");
125
+ }
126
+
127
+ if (this.config.ignoreSSL || process.env.DRDOC_IGNORE_SSL) {
128
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
129
+ }
130
+
131
+ this.config.baseUrl = this.config.baseUrl.replace(/\/$/, "");
132
+
133
+ if (this.config.username && this.config.password) {
134
+ const authStr = `${this.config.username}:${this.config.password}`;
135
+ this.config.authHeader = `Basic ${Buffer.from(authStr).toString("base64")}`;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Liest gespeicherte Anmeldedaten als DrDocConfig aus der JSON-Datei aus, sofern vorhanden.
141
+ */
142
+ private loadCredentials(): void {
143
+ try {
144
+ if (fs.existsSync(this.storageFilePath)) {
145
+ const fileContent = fs.readFileSync(this.storageFilePath, "utf-8");
146
+ const savedConfig: DrDocConfig = JSON.parse(fileContent);
147
+
148
+ // Gespeicherte Werte mit den übergebenen Konfigurationswerten zusammenführen
149
+ this.config = {
150
+ ...this.config,
151
+ ...savedConfig,
152
+ };
153
+ }
154
+ } catch (error) {
155
+ console.warn("Gespeicherte Anmeldedaten konnten nicht geladen werden:", error);
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Speichert das DrDocConfig-Objekt als JSON-Datei ab.
161
+ */
162
+ private saveCredentials(): void {
163
+ try {
164
+ const dataToSave = JSON.stringify(this.config, null, 2);
165
+ fs.writeFileSync(this.storageFilePath, dataToSave, "utf-8");
166
+ msgLog('DD Anmeldedaten wurden gespeichert unter: ', this.storageFilePath);
167
+ } catch (error) {
168
+ throw new Error(`Fehler beim Speichern der Anmeldedaten: ${error instanceof Error ? error.message : String(error)}`);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Erstellt Standard-Header inklusive Session-Cookie und Auth-Header
174
+ */
175
+ private getHeaders(additionalHeaders: Record<string, string> = {}): Record<string, string> {
176
+ const headers: Record<string, string> = { ...additionalHeaders };
177
+
178
+ if (this.config?.sessionCookie) {
179
+ headers["Cookie"] = this.config.sessionCookie;
180
+ } else if (this.config.authHeader) {
181
+ //headers["Authorization"] = this.config.authHeader;
182
+ }
183
+
184
+ return headers;
185
+ }
186
+
187
+ /**
188
+ * Speichert erhaltene Cookies (insbesondere 'uid' für User Sessions)
189
+ */
190
+ private processResponseCookies(response: Response): void {
191
+ const setCookie = response.headers.get("set-cookie");
192
+ if (setCookie) {
193
+ const match = setCookie.match(/uid=([^;]+)/);
194
+ if (match) {
195
+ this.config.sessionCookie = `uid=${match[1]}`;
196
+ // this.saveCredentials(this.config);
197
+ }
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Hilfsmethode für GET-Anfragen
203
+ */
204
+ public async get<T = any>(endpoint: string, params: Record<string, any> = {}): Promise<DrDocResponse<T>> {
205
+ // Verwendung des URL-Objekts zur sauberen Zusammenführung von baseUrl und endpoint
206
+ const url = new URL(endpoint, this.config.baseUrl);
207
+
208
+ if (process.env.DRDOC_DEBUG)
209
+ msgLog("DD Get Head: ", endpoint, params, url);
210
+
211
+ // Befüllung der SearchParams
212
+ Object.entries(params).forEach(([key, val]) => {
213
+ if (val !== undefined && val !== null) {
214
+ if (Array.isArray(val)) {
215
+ // Umgang mit Arrays: Parameter mehrfach anhängen
216
+ val.forEach((item) => url.searchParams.append(key, String(item)));
217
+ } else if (typeof val === "object") {
218
+ url.searchParams.append(key, JSON.stringify(val));
219
+ } else {
220
+ url.searchParams.append(key, String(val));
221
+ }
222
+ }
223
+ });
224
+
225
+ const response = await fetch(url, {
226
+ method: "GET",
227
+ headers: this.getHeaders(),
228
+ });
229
+
230
+ this.processResponseCookies(response);
231
+ return (await response.json()) as DrDocResponse<T>;
232
+ }
233
+
234
+ /**
235
+ * Hilfsmethode für GET-Anfragen
236
+ */
237
+ public async getBlob<T = any>(endpoint: string, params: Record<string, any> = {}): Promise<Blob> {
238
+ // Verwendung des URL-Objekts zur sauberen Zusammenführung von baseUrl und endpoint
239
+ const url = new URL(endpoint, this.config.baseUrl);
240
+
241
+ if (process.env.DRDOC_DEBUG)
242
+ msgLog("DD Get Blob Head: ", endpoint, params, url);
243
+
244
+ // Befüllung der SearchParams
245
+ Object.entries(params).forEach(([key, val]) => {
246
+ if (val !== undefined && val !== null) {
247
+ if (Array.isArray(val)) {
248
+ // Umgang mit Arrays: Parameter mehrfach anhängen
249
+ val.forEach((item) => url.searchParams.append(key, String(item)));
250
+ } else if (typeof val === "object") {
251
+ url.searchParams.append(key, JSON.stringify(val));
252
+ } else {
253
+ url.searchParams.append(key, String(val));
254
+ }
255
+ }
256
+ });
257
+
258
+ const response = await fetch(url, {
259
+ method: "GET",
260
+ headers: this.getHeaders(),
261
+ });
262
+
263
+ this.processResponseCookies(response);
264
+
265
+ return response.blob();
266
+ }
267
+
268
+ /**
269
+ * Hilfsmethode für POST-Anfragen (Form URL-Encoded oder Multipart)
270
+ */
271
+ public async post<T = any>(endpoint: string, data: Record<string, any> = {}): Promise<DrDocResponse<T>> {
272
+ // Verwendung des URL-Objekts zur sauberen Zusammenführung von baseUrl und endpoint
273
+ const url = new URL(endpoint, this.config.baseUrl);
274
+
275
+ if (process.env.DRDOC_DEBUG)
276
+ msgLog("DD Post Head: ", endpoint, data, url);
277
+
278
+ const body = new URLSearchParams();
279
+ Object.entries(data).forEach(([key, val]) => {
280
+ if (val !== undefined && val !== null) {
281
+ if (Array.isArray(val)) {
282
+ // Umgang mit Arrays: Parameter mehrfach anhängen
283
+ val.forEach((item) => body.append(key, String(item)));
284
+ } else if (typeof val === "object") {
285
+ body.append(key, JSON.stringify(val));
286
+ } else {
287
+ body.append(key, String(val));
288
+ }
289
+ }
290
+ });
291
+
292
+ const response = await fetch(url, {
293
+ method: "POST",
294
+ headers: this.getHeaders({
295
+ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
296
+ }),
297
+ body: body.toString(),
298
+ });
299
+
300
+ this.processResponseCookies(response);
301
+ return (await response.json()) as DrDocResponse<T>;
302
+ }
303
+
304
+ // --- Endpoint: Benutzerverwaltung ---
305
+
306
+ public async signin(username?: string, password?: string, totp?: string): Promise<DrDocResponse> {
307
+ const user = username || this.config.username;
308
+ const pass = password || this.config.password;
309
+ const totpCode = totp || this.config.totp;
310
+
311
+ // Ausführung des API-Aufrufs zur Anmeldung
312
+ const response = await this.post("/user", {
313
+ action: "signin",
314
+ username: user,
315
+ password: pass,
316
+ totp: totpCode,
317
+ });
318
+
319
+ // Überprüfung auf erfolgreiche Anmeldung
320
+ if (response && !response.HasError) {
321
+ this.config.username = user;
322
+ this.config.password = pass;
323
+ if (totpCode) {
324
+ this.config.totp = totpCode;
325
+ }
326
+
327
+ // Aktualisierung der internen Variablen (Auth-Header etc.)
328
+ this.applyConfig();
329
+
330
+ // Dauerhaftes Speichern der gesamten DrDocConfig nach erfolgreichem Login
331
+ this.saveCredentials();
332
+
333
+ msgLog('DD: Sign in OK:', this.config);
334
+ }
335
+ else {
336
+
337
+ console.warn('DD: Sign in ERR:', this.config);
338
+ }
339
+
340
+ return response;
341
+ }
342
+
343
+ public async state(): Promise<DrDocResponse> {
344
+
345
+ // Ausführung des API-Aufrufs zur Anmeldung
346
+ const response = await this.post("/user", {
347
+ action: "status",
348
+ });
349
+
350
+ // Überprüfung auf erfolgreiche Anmeldung
351
+ if (response && !response.HasError) {
352
+ msgLog('DD: State OK:', this.config);
353
+ return true;
354
+ }
355
+ else {
356
+ msgError('DD: State ERR:', this.config);
357
+ return false;
358
+ }
359
+ }
360
+
361
+ public async signout(): Promise<DrDocResponse> {
362
+ return this.post("/user", { action: "signout" });
363
+ }
364
+
365
+ public async userStatus(): Promise<DrDocResponse> {
366
+ return this.post("/user", { action: "status" });
367
+ }
368
+
369
+ // --- Endpoint: Metadaten CRUD ---
370
+
371
+ public async getRecord(archive: string, id: string, idField?: string): Promise<DrDocResponse> {
372
+ return this.post("/model/crud", {
373
+ action: "get",
374
+ archive,
375
+ id,
376
+ id_field: idField,
377
+ });
378
+ }
379
+
380
+ public async createRecord(archive: string, value: Record<string, any>): Promise<DrDocResponse> {
381
+ return this.get("/model/crud", {
382
+ action: "create",
383
+ archive,
384
+ value,
385
+ });
386
+ }
387
+
388
+ public async updateRecord(archive: string, value: Record<string, any>): Promise<DrDocResponse> {
389
+ return this.post("/model/crud", {
390
+ action: "set",
391
+ archive,
392
+ value,
393
+ });
394
+ }
395
+
396
+ // VORSICHT!!
397
+ public async removeRecord(archive: string, id: string): Promise<DrDocResponse> {
398
+ return this.post("/model/crud", {
399
+ action: "remove",
400
+ archive,
401
+ id,
402
+ });
403
+ }
404
+
405
+ public async searchFields(
406
+ archive: string,
407
+ value: Record<string, any>,
408
+ options: { selection?: string; count?: number; start?: number } = {}
409
+ ): Promise<DrDocResponse> {
410
+ return this.post("/model/crud", {
411
+ action: "searchfields",
412
+ archive,
413
+ value,
414
+ ...options,
415
+ });
416
+ }
417
+
418
+ public async textRetrieval(
419
+ archive: string,
420
+ queryText: string,
421
+ options: { selection?: string; count?: number; start?: number } = {}
422
+ ): Promise<DrDocResponse> {
423
+ return this.post("/model/crud", {
424
+ action: "textretrieval",
425
+ archive,
426
+ value: queryText,
427
+ ...options,
428
+ });
429
+ }
430
+
431
+ // --- Endpoint: Document ---
432
+
433
+ public async getDocument(archive: string, id: string, idField?: string): Blob {
434
+ return this.getBlob("/model/document", {
435
+ action: "get",
436
+ archive,
437
+ id,
438
+ id_field: idField,
439
+ });
440
+ }
441
+
442
+ // --- Endpoint: Fieldselections / Fieldproperties ---
443
+
444
+ public async getFieldProperty(archive: string, type: string): Promise<DrDocResponse> {
445
+ return this.get("/model/fieldselection", {
446
+ action: "get-fieldproperty",
447
+ archive,
448
+ type,
449
+ });
450
+ }
451
+
452
+ public async getFieldSelection(archive: string, type: string, name: string): Promise<DrDocResponse> {
453
+ return this.get("/model/fieldselection", {
454
+ action: "get-fieldselection",
455
+ archive,
456
+ type,
457
+ name
458
+ });
459
+ }
460
+
461
+ public async listFieldSelections(archive: string, type: string): Promise<DrDocResponse> {
462
+ return this.get("/model/fieldselection", {
463
+ action: "list-fieldselections",
464
+ archive,
465
+ type,
466
+ });
467
+ }
468
+ }
package/src/index.ts ADDED
@@ -0,0 +1,77 @@
1
+ import { drdocTools, getClient } from "./tools";
2
+ import { DrDocClient, DrDocConfig, msgLog, msgInfo, msgError } from "./drdoc-client";
3
+
4
+
5
+ /**
6
+ * Registriert Dr.DOC Tools und Slash Commands im PI Agent Kontext.
7
+ *
8
+ * @param pi - PI Extension Context
9
+ */
10
+ export default function (pi: any): void {
11
+ // Registrierung der Dr.DOC Werkzeuge
12
+ for (const tool of drdocTools) {
13
+ pi.registerTool(tool);
14
+ }
15
+
16
+ // Registrierung der Slash Commands
17
+
18
+ // Login
19
+ pi.registerCommand("drdoc_login", {
20
+ description: "Benutzer anmelden in Dr.DOC über die REST API und speichert die Session.",
21
+ handler: async (args: string, ctx: any) => {
22
+ // Entfernen leerer Strings nach dem String-Split
23
+ const parts = args.trim().split(/\s+/); //.filter(Boolean);
24
+ let [baseUrl, username, password, totp, ignoreSSL] = parts;
25
+
26
+ if (!baseUrl)
27
+ baseUrl = process.env.DRDOC_BASE_URL;
28
+
29
+ if (!baseUrl || !username || !password) {
30
+ msgError("Fehler: Syntax ist `/drdoc-login <baseUrl> <username> <password> <totp> <ignoreSSL:1,0>`");
31
+ return;
32
+ }
33
+
34
+ try {
35
+ //initializeDrDocClient({ baseUrl, username, password, totp, ignoreSSL });
36
+ //const client = new DrDocClient({ baseUrl, username, password, totp, ignoreSSL });
37
+ const client = await getClient({ baseUrl, username, password, totp, ignoreSSL: (ignoreSSL == '1' || ignoreSSL == 'true') });
38
+ if (process.env.DRDOC_DEBUG)
39
+ msgLog('Client: ', client);
40
+
41
+ const response = await client.signin(username, password, totp);
42
+
43
+ if (response.HasError) {
44
+ msgError(`Anmeldung fehlgeschlagen: ${response.Error?.Message}`);
45
+ return;
46
+ }
47
+
48
+ msgInfo("Erfolgreich an Dr.DOC angemeldet. Die Session ist aktiv.");
49
+ } catch (err: any) {
50
+ msgError(`Fehler bei der Verbindung: ${err.message}`);
51
+ }
52
+ },
53
+ });
54
+
55
+ // Login
56
+ pi.registerCommand("drdoc_logout", {
57
+ description: "Benutzer abmelden aus Dr.DOC.",
58
+ handler: async (args: string, ctx: any) => {
59
+ const client = await getClient();
60
+ client.signout();
61
+ }
62
+ });
63
+
64
+ if (process.env.DRDOC_DEBUG) {
65
+ // Test
66
+ pi.registerCommand("drdoc_log_test", {
67
+ description: "Log Test.",
68
+ handler: async (args: string, ctx: any) => {
69
+ const client = await getClient();
70
+ msgLog('Log Test: ', client);
71
+ }
72
+ });
73
+ }
74
+
75
+ }
76
+
77
+ export { DrDocClient, drdocTools };
package/src/tools.ts ADDED
@@ -0,0 +1,407 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import * as os from "os";
4
+
5
+ import { DrDocClient, DrDocConfig, msgLog, msgInfo, msgError } from "./drdoc-client";
6
+
7
+ let clientInstance: DrDocClient | null = null;
8
+
9
+ /**
10
+ * Hilfsfunktion zum Abrufen der initialisierten Instanz.
11
+ */
12
+ export async function getClient(config: DrDocConfig = {} as DrDocConfig, force: Boolean = false): Promise<DrDocClient> {
13
+ if (!clientInstance || force) {
14
+ msgInfo('getClient: init instance');
15
+ clientInstance = new DrDocClient(config);
16
+ // Verbindung testen
17
+ if (await clientInstance.state())
18
+ msgInfo('getClient: state ok');
19
+ else {
20
+ throw new Error("getClient: DrDocClient ist nicht initialisiert. Bitte vorher den Befehl /drdoc-login ausführen.");
21
+ }
22
+ }
23
+ return clientInstance;
24
+ }
25
+
26
+ /**
27
+ * Hilfsfunktion zur Formatierung von Werkzeug-Antworten für das PI Framework.
28
+ * Garantiert stets ein definiertes 'content'-Array im Ergebnis.
29
+ */
30
+ function formatToolResult(data: any, isError: boolean = false) {
31
+ const safeData = data ?? "";
32
+ const textContent = typeof safeData === "string" ? safeData : JSON.stringify(safeData, null, 2);
33
+ return {
34
+ content: [
35
+ {
36
+ type: "text",
37
+ text: isError ? `Fehler: ${textContent}` : textContent,
38
+ },
39
+ ],
40
+ ...(isError ? { isError: true } : {}),
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Führt eine Werkzeug-Aktion sicher aus und fängt Ausnahmen ab,
46
+ * um stets ein valides PI-Antwortformat zu garantieren.
47
+ */
48
+ async function safeExecute<T>(fn: () => Promise<T>) {
49
+ try {
50
+ const result = await fn();
51
+ return formatToolResult(result);
52
+ } catch (error: any) {
53
+ const errorMessage = error?.message || String(error);
54
+ msgError(errorMessage);
55
+ return formatToolResult(errorMessage, true);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Für Tool Execute Aufrufe für Client-basierte Werkzeuge.
61
+ * Überprüft das Vorhandensein aller Pflichtparameter, ruft die 'DrDocClient'-Instanz ab
62
+ * und führt die Ziel-Funktion innerhalb von 'safeExecute' aus.
63
+ *
64
+ * @param requiredParams Liste der erforderlichen Parameter-Namen.
65
+ * @param args Die vom Tool empfangenen Argumente.
66
+ * @param fn Auszuführende Funktion mit dem initialisierten Client und den Argumenten.
67
+ */
68
+ export function safeExecuteClient<A extends Record<string, any> = Record<string, any>, T = any>(
69
+ requiredParams: (keyof A & string)[],
70
+ args: A | undefined,
71
+ fn: (client: DrDocClient, safeArgs: A) => Promise<T>
72
+ ) {
73
+ return safeExecute(async () => {
74
+ const safeArgs = (args || {}) as A;
75
+
76
+ // Überprüfung aller erforderlichen Parameter
77
+ const missing = requiredParams.filter(
78
+ (param) => safeArgs[param] === undefined || safeArgs[param] === null || safeArgs[param] === ""
79
+ );
80
+
81
+ if (missing.length > 0) {
82
+ throw new Error(`Fehlende Pflichtparameter: ${missing.join(", ")} müssen angegeben werden.`);
83
+ }
84
+
85
+ // Abruf der Client-Instanz und Ausführung der Logik
86
+ const client = await getClient();
87
+ return await fn(client, safeArgs);
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Werkzeug-Definitionen für das PI Agent Framework.
93
+ */
94
+ export const drdocTools = [
95
+ {
96
+ name: "drdoc_login_2",
97
+ description: "Meldet den Benutzer in Dr.DOC über die REST API an.",
98
+ parameters: {
99
+ type: "object",
100
+ properties: {
101
+ baseUrl: { type: "string", description: "Basis-URL der Dr.DOC Instanz (z. B. https://drdoc.com)" },
102
+ username: { type: "string", description: "Benutzername" },
103
+ password: { type: "string", description: "Passwort" },
104
+ totp: { type: "string", description: "TOTP F2A" },
105
+ ignoreSSL: { type: "boolean", description: "SSL-Zertifikatsprüfung ignorieren" },
106
+ },
107
+ required: ["baseUrl", "username", "password"],
108
+ },
109
+ execute: async (toolCallId: string, args?: { baseUrl?: string; username?: string; password?: string; totp?: string; ignoreSSL?: boolean }) => {
110
+ return safeExecute(async () => {
111
+ const safeArgs = args || {};
112
+ if (!safeArgs.baseUrl || !safeArgs.username || !safeArgs.password) {
113
+ throw new Error("Fehlende Pflichtparameter: baseUrl, username und password müssen angegeben werden.");
114
+ }
115
+ // getClient mit force: true zur Neu-Initialisierung
116
+ const client = await getClient({
117
+ baseUrl: safeArgs.baseUrl,
118
+ username: safeArgs.username,
119
+ password: safeArgs.password,
120
+ totp: safeArgs.totp,
121
+ ignoreSSL: safeArgs.ignoreSSL,
122
+ }, true);
123
+ return await client.signin(safeArgs.username, safeArgs.password, safeArgs.totp);
124
+ });
125
+ },
126
+ },
127
+ {
128
+ name: "drdoc_properties_fields",
129
+ description: "Liste aller Dr.DOC Felder (Feldnamen) im Dr.DOC Archiv. Diese Funktion **muss** vor 'drdoc_search_fields' aufgerufen werden.",
130
+ parameters: {
131
+ type: "object",
132
+ properties: {
133
+ archive: { type: "string", description: "Name des Dr.DOC Ziel-Archivs" },
134
+ },
135
+ required: ["archive"],
136
+ },
137
+ execute: async (toolCallId: string, args?: { archive?: string }) => {
138
+ if (process.env.DRDOC_DEBUG)
139
+ msgLog('drdoc_properties_fields:', args);
140
+ return safeExecuteClient(["archive"], args, async (client, safeArgs) => {
141
+ const defNameArray = ['STD_AI_INVOICE_IN', 'DD_FIELD_DESC', 'STD_FIELD_DESC'];
142
+ for (let defName of defNameArray) {
143
+ const fs = await client.getFieldSelection(safeArgs.archive, "IMPORT_ASCII", defName);
144
+ if (process.env.DRDOC_DEBUG)
145
+ msgLog('props:', fs);
146
+ if (!fs.HasError && fs.Result)
147
+ return fs.Result;
148
+ }
149
+ return {};
150
+ });
151
+ },
152
+ },
153
+ {
154
+ name: "drdoc_search_fields",
155
+ description: `Führt eine feldspezifische Suche (Feldsuche oder Filtersuche) in einem Dr.DOC Archiv durch.
156
+ Du **musst** zuerst alle Dr.DOC Feldnamen durch 'drdoc_properties_fields' abrufen, und erst danach 'drdoc_search_fields', damit Du weißt in welchen Feldern Du suchen musst.
157
+
158
+ Diese Suche sollte verwendet werden, wenn nach Bereichen oder bestimmten Feldwerten gesucht werden soll (z.B. Firma "*Amazon*" und Datum "%DY%").
159
+ Es kann je Feld eine Suchbedingung bzw. Suchtext eingegeben werden.
160
+ Es wird nur in den angegebenen Feldern gesucht.
161
+ Dokumentation für Suchbedingung / Suchfilter im Parameter value:
162
+ Suchfelder und Suchwerte (flache key-value-pair Liste). Die Datensätze werden danach gefiltert.
163
+ Der Feld-Suchtext bzw. Suchbedingung greift nur für die hier angegebenen Felder.
164
+ Die Suchoperatoren müssen ohne Leerzeichen verkettet werden, also ohne Leerzeichen direkt an die Suchbegriffe angehängt werden (bzw. für NOT-Operator vorangestellt werden).
165
+ Suchoperatoren:
166
+ - * für gefüllte Felder
167
+ - *TEXT* für enthält Feldwert TEXT bzw. trunktierte Suche
168
+ - & als logischer AND Operator
169
+ - "|" (Pippe) als logischer OR Operator
170
+ - ! als logischer NOT Operator als Prefix, muss dem Suchbegriff vorangestellt werden.
171
+ - !* für leere Felder
172
+ - <-> für Datumsbereich, Zeitraum, Bereichssuche, Zahlenbereich; A<->B von A bis einschließlich B; Format für Datumsbereich: DD.MM.YYYY<->DD.MM.YYYY z.B. 01.07.2024<->31.07.2024.
173
+ Beispiele für Suchoperatoren:
174
+ - *TEXT* für trunkierte/Substring Suche nach TEXT (Feldwert enthält TEXT), MUSS zwingend bei unklaren/ungenauen/unspezifischen Eingaben verwendet werden!
175
+ - !*TEXT* für Feldwert enthält TEXT nicht
176
+ - !* für leeren, nicht gefüllte Feldwerte
177
+ - !TEXT für alle Feldwerte, abgesehen von TEXT bzw. alles bis auf TEXT.
178
+ - !A&B für exakte Suche nach B jedoch ohne A
179
+ - "A|B" (Pippe) für exakte Suche nach A oder B
180
+ - !*A*&*B* für Suche nach enthält (Substring) B aber enthält kein A
181
+ - 01.01.2020<->31.12.2020 für Datumssuchbereichs-Suche (Bereichssuche) vom 01.01.2020 bis einschließlich 31.12.2020 (1 Jahr)
182
+ - 01.07.2024<->31.07.2024 für Datumssuchbereichs-Suche (Bereichssuche) vom 01.07.2024 bis einschließlich 31.07.2024 für den Monat Juli 2024 (1 Monat)
183
+ Datumsformat: DD.MM.YYYY
184
+ Zahlenformat: 0.00
185
+ Variablen:
186
+ - %DY% Variable für Datumsbereich im aktuellen/diesen Jahr
187
+ - %DMY% Variable für Datumsbereich im aktuellen/diesen Monat
188
+ - %DWY% Variable für Datumsbereich in der aktuellen/diesen Woche (7 Tage)
189
+ - %B% Variable für angemeldeten Benutzer
190
+ - %D% Variable für aktuelles Datum (heutiger Tag)
191
+ - %D-1% Variable für gestriges Datum bzw. gestern
192
+ - %D-2% Variable für vorgestern
193
+ - %D+1% Variable für morgiges Datum bzw. morgen
194
+ - %D+2% Variable für übermorgen
195
+ Beispiel: Filter für alle Eingangsrechnungen im Zeitraum Juli 2024 (01.07.2024 bis einschließlich 31.07.2024) von Firma Amazon:
196
+ { date: "01.07.2024<->31.07.2024", c_company: "*Amazon*", inout: "0", type: "Rechnung" }
197
+ `,
198
+ parameters: {
199
+ type: "object",
200
+ properties: {
201
+ archive: { type: "string", description: "Name des Archivs" },
202
+ searchValues: {
203
+ type: "object",
204
+ description: "Key-Value Paare für die Feldsuche. Der Key muss Exakt einem Dr.DOC Feldnamen entsprechen (durch das Tool 'drdoc_properties_fields'). Unterstützt Operatoren wie *TEXT*, !*, A<->B",
205
+ },
206
+ selection: { type: "string", description: "Mit Semikolon getrennte Liste auszugebender Felder" },
207
+ count: { type: "number", description: "Maximale Trefferanzahl" },
208
+ },
209
+ required: ["archive", "searchValues"],
210
+ },
211
+ execute: async (toolCallId: string, args?: { archive?: string; searchValues?: Record<string, any>; selection?: string; count?: number }) => {
212
+ if (process.env.DRDOC_DEBUG)
213
+ msgLog('drdoc_search_fields:', args);
214
+ return safeExecuteClient(["archive", "searchValues"], args, async (client, safeArgs) => {
215
+ return await client.searchFields(safeArgs.archive, safeArgs.searchValues, {
216
+ selection: safeArgs.selection,
217
+ count: safeArgs.count,
218
+ });
219
+ });
220
+ },
221
+ },
222
+ {
223
+ name: "drdoc_search_fulltext",
224
+ description: `Führt eine Volltextsuche (Text Retrieval, Freitextsuche, Volltextsuche, Text Retrieval, Full-Text-Search) über alle Felder und Metadaten eines Dr.DOC Archivs durch.
225
+ Die Bedeutung der Felder erhältst Du durch das Tool 'drdoc_properties_fields'.
226
+
227
+ Diese Suche sollte verwendet werden, wenn im Dokumenttext bzw. allen Feldwerten gesucht werden soll, unabhängig davon wo der Text im Dr.DOC Archiv zu finden ist.
228
+ Es muss eine Suchbedingung bzw. Suchtext eingegeben werden, ohne Feldname.
229
+ Es wird eine Suchergebnisliste von vorgefilterten Datensätzen zurückgegeben.
230
+ Suchtext (bzw. Suchbedingung). Die zurückgegebenen Datensätze werden nach diesem Suchtext gefiltert.
231
+ Es soll der Suchtext ohne Feldname angegeben werden. " +Der Suchtext greift für alle Dr.DOC Felder (Volltextsuche), also unabhängig in welchem Feld der Text gefunden wird.
232
+ Die Suchoperatoren müssen ohne Leerzeichen verkettet werden, also ohne Leerzeichen direkt an die Suchbegriffe angehängt werden (bzw. für NOT Operator vorangestellt werden).
233
+ Suchoperatoren:
234
+ - & als logischer AND Operator
235
+ - "|" (Pipe) als logischer OR Operator
236
+ - ! als logischer NOT Operator als Prefix, muss dem Suchbegriff vorangestellt werden.
237
+ Beispiele für Suchoperatoren:
238
+ - !A&B für Suche nach B jedoch ohne A
239
+ - "A|B" für Suche nach A oder B
240
+ Datumsformat: DD.MM.YYYY
241
+ `,
242
+ parameters: {
243
+ type: "object",
244
+ properties: {
245
+ archive: { type: "string", description: "Name des Archivs" },
246
+ queryText: { type: "string", description: "Suchtext oder Suchbedingung" },
247
+ selection: { type: "string", description: "Mit Semikolon getrennte Liste auszugebender Felder" },
248
+ count: { type: "number", description: "Maximale Trefferanzahl" },
249
+ },
250
+ required: ["archive", "queryText"],
251
+ },
252
+ execute: async (toolCallId: string, args?: { archive?: string; queryText?: string; selection?: string; count?: number }) => {
253
+ if (process.env.DRDOC_DEBUG)
254
+ msgLog('drdoc_search_fulltext:', args);
255
+ return safeExecuteClient(["archive", "queryText"], args, async (client, safeArgs) => {
256
+ return await client.textRetrieval(safeArgs.archive, safeArgs.queryText, {
257
+ selection: safeArgs.selection,
258
+ count: safeArgs.count,
259
+ });
260
+ });
261
+ },
262
+ },
263
+ {
264
+ name: "drdoc_get_record",
265
+ description: "Liest einen konkreten Meta-Datensatz anhand seiner ID aus. Die Bedeutung der Felder erhältst Du durch das Tool 'drdoc_properties_fields'.",
266
+ parameters: {
267
+ type: "object",
268
+ properties: {
269
+ archive: { type: "string", description: "Name des Dr.DOC Archivs" },
270
+ id: { type: "string", description: "Datensatz-ID (DrDocGUID oder Dokument-Nr.)" },
271
+ idField: { type: "string", description: "Optionaler Feldname für die ID" },
272
+ },
273
+ required: ["archive", "id"],
274
+ },
275
+ execute: async (toolCallId: string, args?: { archive?: string; id?: string; idField?: string }) => {
276
+ return safeExecuteClient(["archive", "id"], args, async (client, safeArgs) => {
277
+ return await client.getRecord(safeArgs.archive, safeArgs.id, safeArgs.idField);
278
+ });
279
+ },
280
+ },
281
+ {
282
+ name: "drdoc_create_record",
283
+ description: "Erstellt einen neuen Meta-Datensatz in einem Dr.DOC Archiv. Die Bedeutung der Felder erhältst Du durch das Tool 'drdoc_properties_fields'.",
284
+ parameters: {
285
+ type: "object",
286
+ properties: {
287
+ archive: { type: "string", description: "Name des Dr.DOC Ziel-Archivs" },
288
+ value: { type: "object", description: "JSON-Objekt mit den Feldinhalten" },
289
+ },
290
+ required: ["archive", "value"],
291
+ },
292
+ execute: async (toolCallId: string, args?: { archive?: string; value?: Record<string, any> }) => {
293
+ return safeExecuteClient(["archive", "value"], args, async (client, safeArgs) => {
294
+ return await client.createRecord(safeArgs.archive, safeArgs.value);
295
+ });
296
+ },
297
+ },
298
+ /*{
299
+ name: "drdoc_get_document",
300
+ description: "Liest ein Dokumenteninhalt (Blob) anhand seiner ID aus.",
301
+ parameters: {
302
+ type: "object",
303
+ properties: {
304
+ archive: { type: "string", description: "Name des Dr.DOC Archivs" },
305
+ id: { type: "string", description: "Datensatz-ID (DrDocGUID oder Dokument-Nr.)" },
306
+ idField: { type: "string", description: "Optionaler Feldname für die ID" },
307
+ },
308
+ required: ["archive", "id"],
309
+ },
310
+ execute: async (toolCallId: string, args?: { archive?: string; id?: string; idField?: string }) => {
311
+ return safeExecuteClient(["archive", "id"], args, async (client, safeArgs) => {
312
+ return await client.getDocument(safeArgs.archive, safeArgs.id, safeArgs.idField);
313
+ });
314
+ },
315
+ },*/
316
+
317
+ {
318
+ name: "drdoc_get_document",
319
+ description: "Liest den Dokumenteninhalt (Blob) anhand der ID aus, speichert die Datei lokal und bereitet sie für die Anzeige im Pi Agent auf.",
320
+ parameters: {
321
+ type: "object",
322
+ properties: {
323
+ archive: { type: "string", description: "Name des Dr.DOC Archivs" },
324
+ id: { type: "string", description: "Datensatz-ID (DrDocGUID oder Dokument-Nr.)" },
325
+ idField: { type: "string", description: "Optionaler Feldname für die ID" },
326
+ },
327
+ required: ["archive", "id"],
328
+ },
329
+ execute: async (toolCallId: string, args?: { archive?: string; id?: string; idField?: string }) => {
330
+ return safeExecuteClient(["archive", "id"], args, async (client, safeArgs) => {
331
+ // Dokumenten-Blob vom Client abrufen
332
+ const responseData = await client.getDocument(safeArgs.archive, safeArgs.id, safeArgs.idField);
333
+
334
+ // Konvertierung in Node.js Buffer und Ermittlung des MIME-Typs
335
+ let buffer: Buffer;
336
+ let mimeType = "application/octet-stream";
337
+
338
+ if (typeof Blob !== "undefined" && responseData instanceof Blob) {
339
+ mimeType = responseData.type || mimeType;
340
+ const arrayBuffer = await responseData.arrayBuffer();
341
+ buffer = Buffer.from(arrayBuffer);
342
+ } else if (Buffer.isBuffer(responseData)) {
343
+ buffer = responseData;
344
+ } else {
345
+ buffer = Buffer.from(responseData as any);
346
+ }
347
+
348
+ // Download-Ordner im Arbeitsverzeichnis sicherstellen
349
+ //const downloadsDir = path.join(process.cwd());
350
+
351
+ // const downloadsDir = path.join(process.cwd(), "downloads");
352
+
353
+ // Bestimmung des Zielverzeichnisses über das Home-Verzeichnis
354
+ const downloadsDir = process.env.DRDOC_DOWNLOAD_DIR || path.join(os.homedir(), "downloads", "drdoc"); //, "downloads");
355
+
356
+ // 1. Umgebungsvariable, 2. Client-Config, 3. Home-Verzeichnis
357
+ //const downloadsDir = process.env.DRDOC_DOWNLOAD_DIR
358
+ // || client.getConfig?.()?.downloadDir
359
+ // || path.join(os.homedir(), "Downloads");
360
+
361
+ // Alternativ im temporären Verzeichnis des Betriebssystems:
362
+ //const downloadsDir = process.env.DRDOC_DOWNLOAD_DIR || path.join(os.tmpdir(), "drdoc-downloads");
363
+
364
+ if (!fs.existsSync(downloadsDir)) {
365
+ fs.mkdirSync(downloadsDir, { recursive: true });
366
+ }
367
+
368
+ // Dateiendung bestimmen und Dateinamen generieren
369
+ const extension = mimeType.includes("/") ? mimeType.split("/")[1] : "bin";
370
+ const safeId = safeArgs.id.replace(/[^a-zA-Z0-9_-]/g, "_");
371
+ const fileName = `${safeArgs.archive}_${safeId}.${extension}`;
372
+ const filePath = path.join(downloadsDir, fileName);
373
+
374
+ // Datei im Dateisystem ablegen
375
+ fs.writeFileSync(filePath, buffer);
376
+
377
+ // Web-URL für den direkten Aufruf im Browser erzeugen
378
+ const baseUrl = client.getConfig?.()?.baseUrl || "https://drdoc.com";
379
+ const webUrl = new URL("/model/document", baseUrl);
380
+ webUrl.searchParams.set("action", "get");
381
+ webUrl.searchParams.set("archive", safeArgs.archive);
382
+ webUrl.searchParams.set("id", safeArgs.id);
383
+ if (safeArgs.idField) {
384
+ webUrl.searchParams.set("id_field", safeArgs.idField);
385
+ }
386
+ webUrl.searchParams.set("download", "false");
387
+
388
+ // Rückgabe-Objekt für die Darstellung im Pi Agent
389
+ const result: Record<string, any> = {
390
+ message: `Dokument wurde erfolgreich heruntergeladen und lokal gespeichert nach "${filePath}".`,
391
+ filePath: filePath,
392
+ fileName: fileName,
393
+ webUrl: webUrl.toString(),
394
+ mimeType: mimeType,
395
+ sizeBytes: buffer.length,
396
+ };
397
+
398
+ // Bei Bildern wird eine Base64-Data-URL zur direkten Inline-Anzeige hinzugefügt
399
+ if (mimeType.startsWith("image/")) {
400
+ result.imageBase64 = `data:${mimeType};base64,${buffer.toString("base64")}`;
401
+ }
402
+
403
+ return result;
404
+ });
405
+ },
406
+ },
407
+ ];
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "CommonJS",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "rootDir": "./src",
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true
12
+ },
13
+ "include": [
14
+ "src/**/*"
15
+ ]
16
+ }