@frogbotai/plugin-ai-capture 0.0.0-stage → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/blob.d.ts +5 -0
  4. package/dist/blob.d.ts.map +1 -0
  5. package/dist/blob.js +15 -0
  6. package/dist/blob.js.map +1 -0
  7. package/dist/collection.d.ts +3 -0
  8. package/dist/collection.d.ts.map +1 -0
  9. package/dist/collection.js +111 -0
  10. package/dist/collection.js.map +1 -0
  11. package/dist/commands/exportCaptures.d.ts +7 -0
  12. package/dist/commands/exportCaptures.d.ts.map +1 -0
  13. package/dist/commands/exportCaptures.js +73 -0
  14. package/dist/commands/exportCaptures.js.map +1 -0
  15. package/dist/commands/exportCapturesArgs.d.ts +10 -0
  16. package/dist/commands/exportCapturesArgs.d.ts.map +1 -0
  17. package/dist/commands/exportCapturesArgs.js +34 -0
  18. package/dist/commands/exportCapturesArgs.js.map +1 -0
  19. package/dist/commands/exportCapturesStream.d.ts +5 -0
  20. package/dist/commands/exportCapturesStream.d.ts.map +1 -0
  21. package/dist/commands/exportCapturesStream.js +7 -0
  22. package/dist/commands/exportCapturesStream.js.map +1 -0
  23. package/dist/commands/exportTrainingData.d.ts +10 -0
  24. package/dist/commands/exportTrainingData.d.ts.map +1 -0
  25. package/dist/commands/exportTrainingData.js +47 -0
  26. package/dist/commands/exportTrainingData.js.map +1 -0
  27. package/dist/hooks.d.ts +9 -0
  28. package/dist/hooks.d.ts.map +1 -0
  29. package/dist/hooks.js +125 -0
  30. package/dist/hooks.js.map +1 -0
  31. package/dist/index.d.ts +18 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +166 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/storage/filesystem.d.ts +3 -0
  36. package/dist/storage/filesystem.d.ts.map +1 -0
  37. package/dist/storage/filesystem.js +38 -0
  38. package/dist/storage/filesystem.js.map +1 -0
  39. package/dist/training/encodeTrainingData.d.ts +3 -0
  40. package/dist/training/encodeTrainingData.d.ts.map +1 -0
  41. package/dist/training/encodeTrainingData.js +30 -0
  42. package/dist/training/encodeTrainingData.js.map +1 -0
  43. package/dist/training/exportTrainingData.d.ts +4 -0
  44. package/dist/training/exportTrainingData.d.ts.map +1 -0
  45. package/dist/training/exportTrainingData.js +7 -0
  46. package/dist/training/exportTrainingData.js.map +1 -0
  47. package/dist/training/readTrainingData.d.ts +4 -0
  48. package/dist/training/readTrainingData.d.ts.map +1 -0
  49. package/dist/training/readTrainingData.js +60 -0
  50. package/dist/training/readTrainingData.js.map +1 -0
  51. package/dist/training/types.d.ts +13 -0
  52. package/dist/training/types.d.ts.map +1 -0
  53. package/dist/training/types.js +3 -0
  54. package/dist/training/types.js.map +1 -0
  55. package/dist/types.d.ts +43 -0
  56. package/dist/types.d.ts.map +1 -0
  57. package/dist/types.js +3 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +43 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FrogBot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @frogbotai/plugin-ai-capture
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stores opted-in AI request and response bodies as compressed blobs with a content-free index.
4
+
5
+ See the [capture documentation](https://docs.frogbot.ai/plugins/ai-capture).
package/dist/blob.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { CaptureRecord } from './types.js';
2
+ export declare function encodeCapture(capture: CaptureRecord): Promise<Uint8Array>;
3
+ export declare function decodeCapture(bytes: Uint8Array): Promise<CaptureRecord>;
4
+ export declare function captureBlobKey(captureId: string, date?: Date): string;
5
+ //# sourceMappingURL=blob.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blob.d.ts","sourceRoot":"","sources":["../src/blob.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAKhD,wBAAsB,aAAa,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,UAAU,CAAC,CAE/E;AAED,wBAAsB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC,CAE7E;AAED,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,OAAa,GAAG,MAAM,CAE3E"}
package/dist/blob.js ADDED
@@ -0,0 +1,15 @@
1
+ import { promisify } from 'node:util';
2
+ import { gunzip, gzip } from 'node:zlib';
3
+ const gzipAsync = promisify(gzip);
4
+ const gunzipAsync = promisify(gunzip);
5
+ export async function encodeCapture(capture) {
6
+ return gzipAsync(JSON.stringify(capture));
7
+ }
8
+ export async function decodeCapture(bytes) {
9
+ return JSON.parse((await gunzipAsync(bytes)).toString('utf8'));
10
+ }
11
+ export function captureBlobKey(captureId, date = new Date()) {
12
+ return `${date.toISOString().slice(0, 10)}/${captureId}.json.gz`;
13
+ }
14
+
15
+ //# sourceMappingURL=blob.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/blob.ts"],"names":["promisify","gunzip","gzip","gzipAsync","gunzipAsync","encodeCapture","capture","JSON","stringify","decodeCapture","bytes","parse","toString","captureBlobKey","captureId","date","Date","toISOString","slice"],"mappings":"AAAA,SAASA,SAAS,QAAQ,YAAY;AACtC,SAASC,MAAM,EAAEC,IAAI,QAAQ,YAAY;AAIzC,MAAMC,YAAYH,UAAUE;AAC5B,MAAME,cAAcJ,UAAUC;AAE9B,OAAO,eAAeI,cAAcC,OAAsB;IACxD,OAAOH,UAAUI,KAAKC,SAAS,CAACF;AAClC;AAEA,OAAO,eAAeG,cAAcC,KAAiB;IACnD,OAAOH,KAAKI,KAAK,CAAC,AAAC,CAAA,MAAMP,YAAYM,MAAK,EAAGE,QAAQ,CAAC;AACxD;AAEA,OAAO,SAASC,eAAeC,SAAiB,EAAEC,OAAO,IAAIC,MAAM;IACjE,OAAO,GAAGD,KAAKE,WAAW,GAAGC,KAAK,CAAC,GAAG,IAAI,CAAC,EAAEJ,UAAU,QAAQ,CAAC;AAClE","file":"blob.js"}
@@ -0,0 +1,3 @@
1
+ import type { Access, CollectionConfig } from 'frogbot';
2
+ export declare function createCapturesCollection(slug: string, access?: Access): CollectionConfig;
3
+ //# sourceMappingURL=collection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection.d.ts","sourceRoot":"","sources":["../src/collection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAExD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAyCxF"}
@@ -0,0 +1,111 @@
1
+ export function createCapturesCollection(slug, access) {
2
+ const immutable = ()=>false;
3
+ return {
4
+ slug,
5
+ versions: false,
6
+ authorship: false,
7
+ custom: {
8
+ frogbot: {
9
+ internal: true
10
+ }
11
+ },
12
+ labels: {
13
+ singular: 'AI Capture',
14
+ plural: 'AI Captures'
15
+ },
16
+ timestamps: false,
17
+ access: {
18
+ create: immutable,
19
+ update: immutable,
20
+ delete: immutable,
21
+ read: access
22
+ },
23
+ admin: {
24
+ icon: 'database',
25
+ useAsTitle: 'captureId',
26
+ views: [
27
+ {
28
+ type: 'list',
29
+ defaultFields: [
30
+ 'requestId',
31
+ 'operation',
32
+ 'model',
33
+ 'status',
34
+ 'requestedAt'
35
+ ]
36
+ }
37
+ ]
38
+ },
39
+ fields: [
40
+ {
41
+ name: 'captureId',
42
+ type: 'text',
43
+ required: true,
44
+ unique: true,
45
+ index: true
46
+ },
47
+ {
48
+ name: 'requestId',
49
+ type: 'text',
50
+ required: true,
51
+ index: true
52
+ },
53
+ {
54
+ name: 'user',
55
+ type: 'text',
56
+ index: true
57
+ },
58
+ {
59
+ name: 'apiKey',
60
+ type: 'text',
61
+ index: true
62
+ },
63
+ {
64
+ name: 'operation',
65
+ type: 'text',
66
+ required: true,
67
+ index: true
68
+ },
69
+ {
70
+ name: 'model',
71
+ type: 'text',
72
+ required: true,
73
+ index: true
74
+ },
75
+ {
76
+ name: 'blobKey',
77
+ type: 'text',
78
+ required: true,
79
+ unique: true
80
+ },
81
+ {
82
+ name: 'sizeBytes',
83
+ type: 'number',
84
+ required: true
85
+ },
86
+ {
87
+ name: 'status',
88
+ type: 'select',
89
+ required: true,
90
+ options: [
91
+ 'success',
92
+ 'error'
93
+ ],
94
+ index: true
95
+ },
96
+ {
97
+ name: 'requestedAt',
98
+ type: 'date',
99
+ required: true,
100
+ index: true
101
+ },
102
+ {
103
+ name: 'completedAt',
104
+ type: 'date',
105
+ required: true
106
+ }
107
+ ]
108
+ };
109
+ }
110
+
111
+ //# sourceMappingURL=collection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/collection.ts"],"names":["createCapturesCollection","slug","access","immutable","versions","authorship","custom","frogbot","internal","labels","singular","plural","timestamps","create","update","delete","read","admin","icon","useAsTitle","views","type","defaultFields","fields","name","required","unique","index","options"],"mappings":"AAEA,OAAO,SAASA,yBAAyBC,IAAY,EAAEC,MAAe;IACpE,MAAMC,YAAY,IAAM;IAExB,OAAO;QACLF;QACAG,UAAU;QACVC,YAAY;QACZC,QAAQ;YAAEC,SAAS;gBAAEC,UAAU;YAAK;QAAE;QACtCC,QAAQ;YAAEC,UAAU;YAAcC,QAAQ;QAAc;QACxDC,YAAY;QACZV,QAAQ;YAAEW,QAAQV;YAAWW,QAAQX;YAAWY,QAAQZ;YAAWa,MAAMd;QAAO;QAChFe,OAAO;YACLC,MAAM;YACNC,YAAY;YACZC,OAAO;gBACL;oBACEC,MAAM;oBACNC,eAAe;wBAAC;wBAAa;wBAAa;wBAAS;wBAAU;qBAAc;gBAC7E;aACD;QACH;QACAC,QAAQ;YACN;gBAAEC,MAAM;gBAAaH,MAAM;gBAAQI,UAAU;gBAAMC,QAAQ;gBAAMC,OAAO;YAAK;YAC7E;gBAAEH,MAAM;gBAAaH,MAAM;gBAAQI,UAAU;gBAAME,OAAO;YAAK;YAC/D;gBAAEH,MAAM;gBAAQH,MAAM;gBAAQM,OAAO;YAAK;YAC1C;gBAAEH,MAAM;gBAAUH,MAAM;gBAAQM,OAAO;YAAK;YAC5C;gBAAEH,MAAM;gBAAaH,MAAM;gBAAQI,UAAU;gBAAME,OAAO;YAAK;YAC/D;gBAAEH,MAAM;gBAASH,MAAM;gBAAQI,UAAU;gBAAME,OAAO;YAAK;YAC3D;gBAAEH,MAAM;gBAAWH,MAAM;gBAAQI,UAAU;gBAAMC,QAAQ;YAAK;YAC9D;gBAAEF,MAAM;gBAAaH,MAAM;gBAAUI,UAAU;YAAK;YACpD;gBACED,MAAM;gBACNH,MAAM;gBACNI,UAAU;gBACVG,SAAS;oBAAC;oBAAW;iBAAQ;gBAC7BD,OAAO;YACT;YACA;gBAAEH,MAAM;gBAAeH,MAAM;gBAAQI,UAAU;gBAAME,OAAO;YAAK;YACjE;gBAAEH,MAAM;gBAAeH,MAAM;gBAAQI,UAAU;YAAK;SACrD;IACH;AACF","file":"collection.js"}
@@ -0,0 +1,7 @@
1
+ import type { CLICommand } from 'frogbot';
2
+ import type { CaptureStorage } from '../types.js';
3
+ export declare function exportCapturesCommand({ collectionSlug, storage, }: {
4
+ collectionSlug: string;
5
+ storage: CaptureStorage;
6
+ }): CLICommand;
7
+ //# sourceMappingURL=exportCaptures.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exportCaptures.d.ts","sourceRoot":"","sources":["../../src/commands/exportCaptures.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAS,MAAM,SAAS,CAAC;AAEjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAoBlD,wBAAgB,qBAAqB,CAAC,EACpC,cAAc,EACd,OAAO,GACR,EAAE;IACD,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,cAAc,CAAC;CACzB,GAAG,UAAU,CAmCb"}
@@ -0,0 +1,73 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { promisify } from 'node:util';
3
+ import { gunzip } from 'node:zlib';
4
+ import { parseExportCapturesArgs } from './exportCapturesArgs.js';
5
+ import { writeCaptureLine } from './exportCapturesStream.js';
6
+ const gunzipAsync = promisify(gunzip);
7
+ function whereFor(args) {
8
+ const and = [];
9
+ if (args.user) and.push({
10
+ user: {
11
+ equals: args.user
12
+ }
13
+ });
14
+ if (args.apiKey) and.push({
15
+ apiKey: {
16
+ equals: args.apiKey
17
+ }
18
+ });
19
+ if (args.operation) and.push({
20
+ operation: {
21
+ equals: args.operation
22
+ }
23
+ });
24
+ if (args.from) {
25
+ and.push({
26
+ requestedAt: {
27
+ greater_than_equal: new Date(args.from).toISOString()
28
+ }
29
+ });
30
+ }
31
+ if (args.to) and.push({
32
+ requestedAt: {
33
+ less_than_equal: new Date(args.to).toISOString()
34
+ }
35
+ });
36
+ return and.length ? {
37
+ and
38
+ } : undefined;
39
+ }
40
+ export function exportCapturesCommand({ collectionSlug, storage }) {
41
+ return async ({ args, getFrogBot })=>{
42
+ const parsed = parseExportCapturesArgs(args);
43
+ const frogbot = await getFrogBot({
44
+ disableOnInit: true
45
+ });
46
+ const destination = parsed.output ? createWriteStream(parsed.output) : undefined;
47
+ const output = destination ?? process.stdout;
48
+ let page = 1;
49
+ while(true){
50
+ const result = await frogbot.find({
51
+ collection: collectionSlug,
52
+ where: whereFor(parsed),
53
+ depth: 0,
54
+ limit: 100,
55
+ page,
56
+ sort: 'requestedAt',
57
+ overrideAccess: true
58
+ });
59
+ for (const value of result.docs){
60
+ const blobKey = String(value.blobKey);
61
+ const json = (await gunzipAsync(await storage.get(blobKey))).toString('utf8');
62
+ await writeCaptureLine(output, json);
63
+ }
64
+ if (!result.hasNextPage) break;
65
+ page = result.nextPage ?? page + 1;
66
+ }
67
+ if (destination) {
68
+ await new Promise((resolve, reject)=>destination.end((error)=>error ? reject(error) : resolve()));
69
+ }
70
+ };
71
+ }
72
+
73
+ //# sourceMappingURL=exportCaptures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/commands/exportCaptures.ts"],"names":["createWriteStream","promisify","gunzip","parseExportCapturesArgs","writeCaptureLine","gunzipAsync","whereFor","args","and","user","push","equals","apiKey","operation","from","requestedAt","greater_than_equal","Date","toISOString","to","less_than_equal","length","undefined","exportCapturesCommand","collectionSlug","storage","getFrogBot","parsed","frogbot","disableOnInit","destination","output","process","stdout","page","result","find","collection","where","depth","limit","sort","overrideAccess","value","docs","blobKey","String","json","get","toString","hasNextPage","nextPage","Promise","resolve","reject","end","error"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,UAAU;AAC5C,SAASC,SAAS,QAAQ,YAAY;AACtC,SAASC,MAAM,QAAQ,YAAY;A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OAAOhC,SAASqB;gBAChBY,OAAO;gBACPC,OAAO;gBACPN;gBACAO,MAAM;gBACNC,gBAAgB;YAClB;YAEA,KAAK,MAAMC,SAASR,OAAOS,IAAI,CAAE;gBAC/B,MAAMC,UAAUC,OAAO,AAACH,MAAkCE,OAAO;gBACjE,MAAME,OAAO,AAAC,CAAA,MAAM1C,YAAY,MAAMoB,QAAQuB,GAAG,CAACH,SAAQ,EAAGI,QAAQ,CAAC;gBACtE,MAAM7C,iBAAiB2B,QAAQgB;YACjC;YAEA,IAAI,CAACZ,OAAOe,WAAW,EAAE;YACzBhB,OAAOC,OAAOgB,QAAQ,IAAIjB,OAAO;QACnC;QAEA,IAAIJ,aAAa;YACf,MAAM,IAAIsB,QAAc,CAACC,SAASC,SAChCxB,YAAYyB,GAAG,CAAC,CAACC,QAAmBA,QAAQF,OAAOE,SAASH;QAEhE;IACF;AACF","file":"exportCaptures.js"}
@@ -0,0 +1,10 @@
1
+ export type ExportCapturesArgs = {
2
+ output?: string;
3
+ user?: string;
4
+ apiKey?: string;
5
+ from?: string;
6
+ to?: string;
7
+ operation?: string;
8
+ };
9
+ export declare function parseExportCapturesArgs(args: string[]): ExportCapturesArgs;
10
+ //# sourceMappingURL=exportCapturesArgs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exportCapturesArgs.d.ts","sourceRoot":"","sources":["../../src/commands/exportCapturesArgs.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,kBAAkB,CAwB1E"}
@@ -0,0 +1,34 @@
1
+ export function parseExportCapturesArgs(args) {
2
+ const parsed = {};
3
+ const names = new Set([
4
+ '--output',
5
+ '--user',
6
+ '--api-key',
7
+ '--from',
8
+ '--to',
9
+ '--operation'
10
+ ]);
11
+ for(let index = 0; index < args.length; index += 1){
12
+ const [flag, inlineValue] = args[index].split(/=(.*)/s);
13
+ if (!names.has(flag)) throw new Error(`unknown option ${flag}`);
14
+ const value = inlineValue ?? args[++index];
15
+ if (value === undefined) throw new Error(`missing value for ${flag}`);
16
+ if (flag === '--output') parsed.output = value;
17
+ if (flag === '--user') parsed.user = value;
18
+ if (flag === '--api-key') parsed.apiKey = value;
19
+ if (flag === '--from') parsed.from = value;
20
+ if (flag === '--to') parsed.to = value;
21
+ if (flag === '--operation') parsed.operation = value;
22
+ }
23
+ for (const name of [
24
+ 'from',
25
+ 'to'
26
+ ]){
27
+ if (parsed[name] && Number.isNaN(new Date(parsed[name]).getTime())) {
28
+ throw new Error(`--${name} must be a valid date`);
29
+ }
30
+ }
31
+ return parsed;
32
+ }
33
+
34
+ //# sourceMappingURL=exportCapturesArgs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/commands/exportCapturesArgs.ts"],"names":["parseExportCapturesArgs","args","parsed","names","Set","index","length","flag","inlineValue","split","has","Error","value","undefined","output","user","apiKey","from","to","operation","name","Number","isNaN","Date","getTime"],"mappings":"AASA,OAAO,SAASA,wBAAwBC,IAAc;IACpD,MAAMC,SAA6B,CAAC;IACpC,MAAMC,QAAQ,IAAIC,IAAI;QAAC;QAAY;QAAU;QAAa;QAAU;QAAQ;KAAc;IAE1F,IAAK,IAAIC,QAAQ,GAAGA,QAAQJ,KAAKK,MAAM,EAAED,SAAS,EAAG;QACnD,MAAM,CAACE,MAAMC,YAAY,GAAGP,IAAI,CAACI,MAAM,CAACI,KAAK,CAAC;QAC9C,IAAI,CAACN,MAAMO,GAAG,CAACH,OAAO,MAAM,IAAII,MAAM,CAAC,eAAe,EAAEJ,MAAM;QAC9D,MAAMK,QAAQJ,eAAeP,IAAI,CAAC,EAAEI,MAAM;QAC1C,IAAIO,UAAUC,WAAW,MAAM,IAAIF,MAAM,CAAC,kBAAkB,EAAEJ,MAAM;QACpE,IAAIA,SAAS,YAAYL,OAAOY,MAAM,GAAGF;QACzC,IAAIL,SAAS,UAAUL,OAAOa,IAAI,GAAGH;QACrC,IAAIL,SAAS,aAAaL,OAAOc,MAAM,GAAGJ;QAC1C,IAAIL,SAAS,UAAUL,OAAOe,IAAI,GAAGL;QACrC,IAAIL,SAAS,QAAQL,OAAOgB,EAAE,GAAGN;QACjC,IAAIL,SAAS,eAAeL,OAAOiB,SAAS,GAAGP;IACjD;IAEA,KAAK,MAAMQ,QAAQ;QAAC;QAAQ;KAAK,CAAW;QAC1C,IAAIlB,MAAM,CAACkB,KAAK,IAAIC,OAAOC,KAAK,CAAC,IAAIC,KAAKrB,MAAM,CAACkB,KAAK,EAAEI,OAAO,KAAK;YAClE,MAAM,IAAIb,MAAM,CAAC,EAAE,EAAES,KAAK,qBAAqB,CAAC;QAClD;IACF;IAEA,OAAOlB;AACT","file":"exportCapturesArgs.js"}
@@ -0,0 +1,5 @@
1
+ export type CaptureOutput = {
2
+ write(value: string, callback: (error?: Error | null) => void): boolean;
3
+ };
4
+ export declare function writeCaptureLine(output: CaptureOutput, json: string): Promise<void>;
5
+ //# sourceMappingURL=exportCapturesStream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exportCapturesStream.d.ts","sourceRoot":"","sources":["../../src/commands/exportCapturesStream.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,IAAI,KAAK,IAAI,GAAG,OAAO,CAAC;CACzE,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAInF"}
@@ -0,0 +1,7 @@
1
+ export function writeCaptureLine(output, json) {
2
+ return new Promise((resolve, reject)=>{
3
+ output.write(`${json}\n`, (error)=>error ? reject(error) : resolve());
4
+ });
5
+ }
6
+
7
+ //# sourceMappingURL=exportCapturesStream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/commands/exportCapturesStream.ts"],"names":["writeCaptureLine","output","json","Promise","resolve","reject","write","error"],"mappings":"AAIA,OAAO,SAASA,iBAAiBC,MAAqB,EAAEC,IAAY;IAClE,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3BJ,OAAOK,KAAK,CAAC,GAAGJ,KAAK,EAAE,CAAC,EAAE,CAACK,QAAWA,QAAQF,OAAOE,SAASH;IAChE;AACF","file":"exportCapturesStream.js"}
@@ -0,0 +1,10 @@
1
+ import type { CLICommand, Where } from 'frogbot';
2
+ type ParsedArgs = {
3
+ where?: Where;
4
+ output?: string;
5
+ pageSize?: number;
6
+ };
7
+ export declare function parseExportTrainingDataArgs(args: string[]): ParsedArgs;
8
+ export declare const exportTrainingDataCommand: CLICommand;
9
+ export {};
10
+ //# sourceMappingURL=exportTrainingData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exportTrainingData.d.ts","sourceRoot":"","sources":["../../src/commands/exportTrainingData.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAIjD,KAAK,UAAU,GAAG;IAChB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,UAAU,CAgCtE;AAED,eAAO,MAAM,yBAAyB,EAAE,UAUvC,CAAC"}
@@ -0,0 +1,47 @@
1
+ import { createWriteStream } from 'node:fs';
2
+ import { Writable } from 'node:stream';
3
+ import { exportTrainingData } from '../training/exportTrainingData.js';
4
+ export function parseExportTrainingDataArgs(args) {
5
+ const parsed = {};
6
+ for(let index = 0; index < args.length; index += 1){
7
+ const [flag, inlineValue] = args[index].split(/=(.*)/s);
8
+ const value = inlineValue ?? args[++index];
9
+ if (value === undefined) {
10
+ throw new Error(`missing value for ${flag}`);
11
+ }
12
+ if (flag === '--where') {
13
+ try {
14
+ parsed.where = JSON.parse(value);
15
+ } catch {
16
+ throw new Error('--where must be valid JSON');
17
+ }
18
+ } else if (flag === '--output') {
19
+ parsed.output = value;
20
+ } else if (flag === '--page-size') {
21
+ const pageSize = Number(value);
22
+ if (!Number.isInteger(pageSize) || pageSize < 1) {
23
+ throw new Error('--page-size must be a positive integer');
24
+ }
25
+ parsed.pageSize = pageSize;
26
+ } else {
27
+ throw new Error(`unknown option ${flag}`);
28
+ }
29
+ }
30
+ return parsed;
31
+ }
32
+ export const exportTrainingDataCommand = async ({ args, getFrogBot })=>{
33
+ const { where, output, pageSize } = parseExportTrainingDataArgs(args);
34
+ const frogbot = await getFrogBot({
35
+ disableOnInit: true
36
+ });
37
+ const stream = exportTrainingData(frogbot, {
38
+ where,
39
+ pageSize,
40
+ overrideAccess: true
41
+ });
42
+ const destination = output ? createWriteStream(output) : process.stdout;
43
+ await stream.pipeTo(Writable.toWeb(destination));
44
+ if (output) process.stdout.write(`[frogbot] training data written to ${output}\n`);
45
+ };
46
+
47
+ //# sourceMappingURL=exportTrainingData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/commands/exportTrainingData.ts"],"names":["createWriteStream","Writable","exportTrainingData","parseExportTrainingDataArgs","args","parsed","index","length","flag","inlineValue","split","value","undefined","Error","where","JSON","parse","output","pageSize","Number","isInteger","exportTrainingDataCommand","getFrogBot","frogbot","disableOnInit","stream","overrideAccess","destination","process","stdout","pipeTo","toWeb","write"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,UAAU;AAC5C,SAASC,QAAQ,Q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B,SAAS8B,KAAK,CAACJ;IAEnC,IAAIV,QAAQW,QAAQC,MAAM,CAACG,KAAK,CAAC,CAAC,mCAAmC,EAAEf,OAAO,EAAE,CAAC;AACnF,EAAE","file":"exportTrainingData.js"}
@@ -0,0 +1,9 @@
1
+ import type { AIHooks } from 'frogbot';
2
+ import type { AICapturePluginOptions, CaptureStorage } from './types.js';
3
+ type HookOptions = Required<Pick<AICapturePluginOptions, 'enabled' | 'maxBodyBytes' | 'sampleRate'>> & {
4
+ collectionSlug: string;
5
+ storage: CaptureStorage;
6
+ };
7
+ export declare function createCaptureHooks(options: HookOptions): AIHooks;
8
+ export {};
9
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAKV,OAAO,EAER,MAAM,SAAS,CAAC;AAGjB,OAAO,KAAK,EAAE,sBAAsB,EAAiB,cAAc,EAAE,MAAM,YAAY,CAAC;AAWxF,KAAK,WAAW,GAAG,QAAQ,CACzB,IAAI,CAAC,sBAAsB,EAAE,SAAS,GAAG,cAAc,GAAG,YAAY,CAAC,CACxE,GAAG;IACF,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,cAAc,CAAC;CACzB,CAAC;AAyEF,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAwDhE"}
package/dist/hooks.js ADDED
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { captureBlobKey, encodeCapture } from './blob.js';
3
+ const languageOperations = new Set([
4
+ 'chat.completions',
5
+ 'messages',
6
+ 'responses'
7
+ ]);
8
+ const stateKey = 'frogbotCapture';
9
+ function errorValue(error) {
10
+ if (error instanceof Error) return {
11
+ name: error.name,
12
+ message: error.message
13
+ };
14
+ return {
15
+ message: String(error)
16
+ };
17
+ }
18
+ function logFailure(req, error) {
19
+ req?.frogbot.logger.error({
20
+ err: error
21
+ }, '[plugin-ai-capture] capture failed');
22
+ }
23
+ async function persist(args, options) {
24
+ const state = args.context[stateKey];
25
+ if (!state?.enabled || !state.request || !state.captureId || !args.req) return;
26
+ const requestedAt = new Date(args.startedAt).toISOString();
27
+ const completedAt = new Date().toISOString();
28
+ const user = args.req.user;
29
+ const apiKeyId = user?._strategy === 'api-key' && (typeof user.apiKeyId === 'string' || typeof user.apiKeyId === 'number') ? user.apiKeyId : undefined;
30
+ const apiKey = apiKeyId !== undefined ? String(apiKeyId) : undefined;
31
+ const capture = {
32
+ captureId: state.captureId,
33
+ requestId: args.requestId,
34
+ operation: args.operation,
35
+ model: args.model,
36
+ provider: args.provider,
37
+ requestedAt,
38
+ completedAt,
39
+ user: args.req.user?.id,
40
+ apiKey,
41
+ request: state.request,
42
+ ...'error' in args ? {
43
+ error: errorValue(args.error)
44
+ } : {
45
+ response: args.response
46
+ }
47
+ };
48
+ if (Buffer.byteLength(JSON.stringify(capture)) > options.maxBodyBytes) {
49
+ throw new Error(`capture exceeds maxBodyBytes (${options.maxBodyBytes})`);
50
+ }
51
+ const bytes = await encodeCapture(capture);
52
+ const blobKey = captureBlobKey(capture.captureId, new Date(args.startedAt));
53
+ await options.storage.put(blobKey, bytes);
54
+ await args.req.frogbot.create({
55
+ collection: options.collectionSlug,
56
+ data: {
57
+ captureId: capture.captureId,
58
+ requestId: capture.requestId,
59
+ user: capture.user == null ? undefined : String(capture.user),
60
+ apiKey,
61
+ operation: capture.operation,
62
+ model: capture.model,
63
+ blobKey,
64
+ sizeBytes: bytes.byteLength,
65
+ status: capture.error ? 'error' : 'success',
66
+ requestedAt,
67
+ completedAt
68
+ },
69
+ overrideAccess: true,
70
+ req: args.req
71
+ });
72
+ }
73
+ export function createCaptureHooks(options) {
74
+ return {
75
+ beforeOperation: [
76
+ (args)=>{
77
+ if (!languageOperations.has(args.operation)) return;
78
+ let enabled = options.enabled;
79
+ let sampleRate = options.sampleRate;
80
+ const user = args.req?.user;
81
+ const actor = user?._strategy === 'api-key' && user.apiKey && typeof user.apiKey === 'object' ? user.apiKey : user;
82
+ if (typeof actor?.capture === 'boolean') enabled = actor.capture;
83
+ if (actor?.capture === 'enabled') enabled = true;
84
+ if (actor?.capture === 'disabled') enabled = false;
85
+ if (typeof actor?.captureSampleRate === 'number') sampleRate = actor.captureSampleRate;
86
+ args.context[stateKey] = {
87
+ enabled: enabled && Math.random() < sampleRate
88
+ };
89
+ }
90
+ ],
91
+ beforeUpstream: [
92
+ (args)=>{
93
+ const state = args.context[stateKey];
94
+ if (!state?.enabled) return;
95
+ const request = {
96
+ messages: args.messages,
97
+ system: args.system,
98
+ tools: args.tools,
99
+ params: args.params ? {
100
+ ...args.params
101
+ } : undefined
102
+ };
103
+ if (Buffer.byteLength(JSON.stringify(request)) > options.maxBodyBytes) {
104
+ state.enabled = false;
105
+ logFailure(args.req, new Error(`capture exceeds maxBodyBytes (${options.maxBodyBytes})`));
106
+ return;
107
+ }
108
+ state.captureId = randomUUID();
109
+ state.request = structuredClone(request);
110
+ }
111
+ ],
112
+ afterUpstream: [
113
+ (args)=>{
114
+ void persist(args, options).catch((error)=>logFailure(args.req, error));
115
+ }
116
+ ],
117
+ afterError: [
118
+ (args)=>{
119
+ void persist(args, options).catch((error)=>logFailure(args.req, error));
120
+ }
121
+ ]
122
+ };
123
+ }
124
+
125
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks.ts"],"names":["randomUUID","captureBlobKey","encodeCapture","languageOperations","Set","stateKey","errorValue","error","Error","name","message","String","logFailure","req","frogbot","logger","err","persist","args","options","state","context","enabled","request","captureId","requestedAt","Date","startedAt","toISOString","completedAt","user","apiKeyId","_strategy","undefined","apiKey","capture","requestId","operation","model","provider","id","response","Buffer","byteLength","JSON","stringify","maxBodyBytes","bytes","blobKey","storage","put","create","collection","collectionSlug","data","sizeBytes","status","overrideAccess","createCaptureHooks","beforeOperation","has","sampleRate","actor","captureSampleRate","Math","random","beforeUpstream","messages","system","tools","params","structuredClone","afterUpstream","catch","afterError"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAc;AAWzC,SAASC,cAAc,EAAEC,aAAa,QAAQ,YAAY;AAG1D,MAAMC,qBAAqB,IAAIC,IAAI;IAAC;IAAoB;IAAY;CAAY;AAChF,MAAMC,WAAW;AAejB,SAASC,WAAWC,KAAc;IAChC,IAAIA,iBAAiBC,OAAO,OAAO;QAAEC,MAAMF,MAAME,IAAI;QAAEC,SAASH,MAAMG,OAAO;IAAC;IAE9E,OAAO;QAAEA,SAASC,OAAOJ;IAAO;AAClC;AAEA,SAASK,WAAWC,GAA+B,EAAEN,KAAc;IACjEM,KAAKC,QAAQC,OAAOR,MAAM;QAAES,KAAKT;IAAM,GAAG;AAC5C;AAEA,eAAeU,QACbC,IAAoD,EACpDC,OAAoB;IAEpB,MAAMC,QAAQF,KAAKG,OAAO,CAAChB,SAAS;IACpC,IAAI,CAACe,OAAOE,WAAW,CAACF,MAAMG,OAAO,IAAI,CAACH,MAAMI,SAAS,IAAI,CAACN,KAAKL,GAAG,EAAE;IACxE,MAAMY,cAAc,IAAIC,KAAKR,KAAKS,SAAS,EAAEC,WAAW;IACxD,MAAMC,cAAc,IAAIH,OAAOE,WAAW;IAE1C,MAAME,OAAOZ,KAAKL,GAAG,CAACiB,IAAI;IAE1B,MAAMC,WACJD,MAAME,cAAc,aACnB,CAAA,OAAOF,KAAKC,QAAQ,KAAK,YAAY,OAAOD,KAAKC,QAAQ,KAAK,QAAO,IAClED,KAAKC,QAAQ,GACbE;IAEN,MAAMC,SAASH,aAAaE,YAAYtB,OAAOoB,YAAYE;IAE3D,MAAME,UAAyB;QAC7BX,WAAWJ,MAAMI,SAAS;QAC1BY,WAAWlB,KAAKkB,SAAS;QACzBC,WAAWnB,KAAKmB,SAAS;QACzBC,OAAOpB,KAAKoB,KAAK;QACjBC,UAAUrB,KAAKqB,QAAQ;QACvBd;QACAI;QACAC,MAAMZ,KAAKL,G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AKD,QAAQC,MAAMC,SAASsD,KAAK,CAAC,CAAClE,QAAUK,WAAWM,KAAKL,GAAG,EAAEN;YACpE;SACD;IACH;AACF","file":"hooks.js"}
@@ -0,0 +1,18 @@
1
+ import { type Plugin } from 'frogbot';
2
+ import type { AICapturePluginOptions, CaptureStorage } from './types.js';
3
+ export { decodeCapture, encodeCapture } from './blob.js';
4
+ export { createCapturesCollection } from './collection.js';
5
+ export { filesystemCaptureStorage } from './storage/filesystem.js';
6
+ export { exportTrainingData } from './training/exportTrainingData.js';
7
+ export type { ReadTrainingDataOptions, TrainingDataDocument, TrainingDataRecord, } from './training/types.js';
8
+ export type { AICapturePluginOptions, CaptureRecord, CaptureStorage } from './types.js';
9
+ type CaptureResolvedOptions = AICapturePluginOptions & Required<Pick<AICapturePluginOptions, 'collectionSlug' | 'maxBodyBytes' | 'sampleRate'>> & {
10
+ storage: CaptureStorage;
11
+ };
12
+ declare module 'frogbot' {
13
+ interface RegisteredPlugins {
14
+ 'plugin-ai-capture': CaptureResolvedOptions;
15
+ }
16
+ }
17
+ export declare function aiCapturePlugin(options?: AICapturePluginOptions): Plugin;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4D,KAAK,MAAM,EAAE,MAAM,SAAS,CAAC;AAOhG,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,kCAAkC,CAAC;AACtE,YAAY,EACV,uBAAuB,EACvB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,sBAAsB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAExF,KAAK,sBAAsB,GAAG,sBAAsB,GAClD,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE,gBAAgB,GAAG,cAAc,GAAG,YAAY,CAAC,CAAC,GAAG;IACzF,OAAO,EAAE,cAAc,CAAC;CACzB,CAAC;AAEJ,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAU,iBAAiB;QACzB,mBAAmB,EAAE,sBAAsB,CAAC;KAC7C;CACF;AAoHD,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,MAAM,CAsB5E"}
package/dist/index.js ADDED
@@ -0,0 +1,166 @@
1
+ import { definePlugin, FROGBOT_QUEUE } from 'frogbot';
2
+ import { createCapturesCollection } from './collection.js';
3
+ import { exportCapturesCommand } from './commands/exportCaptures.js';
4
+ import { exportTrainingDataCommand } from './commands/exportTrainingData.js';
5
+ import { createCaptureHooks } from './hooks.js';
6
+ import { filesystemCaptureStorage } from './storage/filesystem.js';
7
+ export { decodeCapture, encodeCapture } from './blob.js';
8
+ export { createCapturesCollection } from './collection.js';
9
+ export { filesystemCaptureStorage } from './storage/filesystem.js';
10
+ export { exportTrainingData } from './training/exportTrainingData.js';
11
+ function validateRate(value, name) {
12
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
13
+ throw new Error(`[plugin-ai-capture] ${name} must be between 0 and 1.`);
14
+ }
15
+ }
16
+ const aiCapture = definePlugin({
17
+ slug: 'plugin-ai-capture',
18
+ order: 10,
19
+ plugin: ({ config, options, plugins })=>{
20
+ if (!config.ai) throw new Error('[plugin-ai-capture] AI configuration is required.');
21
+ const { collectionSlug, storage } = options;
22
+ const hooks = createCaptureHooks({
23
+ enabled: options.enabled ?? false,
24
+ sampleRate: options.sampleRate,
25
+ maxBodyBytes: options.maxBodyBytes,
26
+ collectionSlug,
27
+ storage
28
+ });
29
+ const captureFields = [
30
+ {
31
+ name: 'capture',
32
+ type: 'select',
33
+ defaultValue: 'inherit',
34
+ options: [
35
+ 'inherit',
36
+ 'enabled',
37
+ 'disabled'
38
+ ]
39
+ },
40
+ {
41
+ name: 'captureSampleRate',
42
+ type: 'number',
43
+ min: 0,
44
+ max: 1
45
+ }
46
+ ];
47
+ const apiKeysSlug = plugins['plugin-api-keys']?.options?.collectionSlug;
48
+ const collections = config.collections.map((collection)=>collection.slug === apiKeysSlug ? {
49
+ ...collection,
50
+ fields: [
51
+ ...collection.fields,
52
+ ...captureFields
53
+ ]
54
+ } : collection);
55
+ const retention = options.retention;
56
+ const task = retention ? {
57
+ slug: `frogbot-prune-${collectionSlug}`,
58
+ interfaceName: `TaskFrogBot-prune-${collectionSlug}`,
59
+ schedule: [
60
+ {
61
+ cron: retention.cron ?? '0 0 * * *',
62
+ queue: FROGBOT_QUEUE
63
+ }
64
+ ],
65
+ handler: async ({ req })=>{
66
+ const cutoff = new Date(Date.now() - retention.days * 86_400_000).toISOString();
67
+ while(true){
68
+ const result = await req.frogbot.find({
69
+ collection: collectionSlug,
70
+ where: {
71
+ requestedAt: {
72
+ less_than: cutoff
73
+ }
74
+ },
75
+ limit: 100,
76
+ sort: 'requestedAt',
77
+ depth: 0,
78
+ overrideAccess: true,
79
+ req
80
+ });
81
+ if (!result.docs.length) break;
82
+ for (const doc of result.docs){
83
+ await storage.delete(doc.blobKey);
84
+ await req.frogbot.delete({
85
+ collection: collectionSlug,
86
+ id: doc.id,
87
+ depth: 0,
88
+ overrideAccess: true,
89
+ req
90
+ });
91
+ }
92
+ }
93
+ return {
94
+ output: {}
95
+ };
96
+ }
97
+ } : undefined;
98
+ return {
99
+ ...config,
100
+ cli: {
101
+ ...config.cli,
102
+ commands: {
103
+ ...config.cli?.commands,
104
+ 'export:captures': exportCapturesCommand({
105
+ collectionSlug,
106
+ storage
107
+ }),
108
+ 'export:training-data': exportTrainingDataCommand
109
+ }
110
+ },
111
+ collections: [
112
+ ...collections,
113
+ createCapturesCollection(collectionSlug, options.access)
114
+ ],
115
+ jobs: task ? {
116
+ ...config.jobs,
117
+ tasks: [
118
+ ...config.jobs?.tasks ?? [],
119
+ task
120
+ ]
121
+ } : config.jobs,
122
+ ai: {
123
+ ...config.ai,
124
+ hooks: {
125
+ ...config.ai.hooks,
126
+ beforeOperation: [
127
+ ...config.ai.hooks?.beforeOperation ?? [],
128
+ ...hooks.beforeOperation ?? []
129
+ ],
130
+ beforeUpstream: [
131
+ ...hooks.beforeUpstream ?? [],
132
+ ...config.ai.hooks?.beforeUpstream ?? []
133
+ ],
134
+ afterUpstream: [
135
+ ...config.ai.hooks?.afterUpstream ?? [],
136
+ ...hooks.afterUpstream ?? []
137
+ ],
138
+ afterError: [
139
+ ...config.ai.hooks?.afterError ?? [],
140
+ ...hooks.afterError ?? []
141
+ ]
142
+ }
143
+ }
144
+ };
145
+ }
146
+ });
147
+ export function aiCapturePlugin(options = {}) {
148
+ const sampleRate = options.sampleRate ?? 1;
149
+ const maxBodyBytes = options.maxBodyBytes ?? 10 * 1024 * 1024;
150
+ validateRate(sampleRate, 'sampleRate');
151
+ if (!Number.isInteger(maxBodyBytes) || maxBodyBytes < 1) {
152
+ throw new Error('[plugin-ai-capture] maxBodyBytes must be a positive integer.');
153
+ }
154
+ if (options.retention && (!Number.isInteger(options.retention.days) || options.retention.days < 1)) {
155
+ throw new Error('[plugin-ai-capture] retention.days must be a positive integer.');
156
+ }
157
+ return aiCapture({
158
+ ...options,
159
+ collectionSlug: options.collectionSlug ?? 'ai-captures',
160
+ sampleRate,
161
+ maxBodyBytes,
162
+ storage: options.storage ?? filesystemCaptureStorage(options.storageRoot)
163
+ });
164
+ }
165
+
166
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":["definePlugin","FROGBOT_QUEUE","createCapturesCollection","exportCapturesCommand","exportTrainingDataCommand","createCaptureHooks","filesystemCaptureStorage","decodeCapture","encodeCapture","exportTrainingData","validateRate","value","name","Number","isFinite","Error","aiCapture","slug","order","plugin","config","options","plugins","ai","collectionSlug","storage","hooks","enabled","sampleRate","maxBodyBytes","captureFields","type","defaultValue","min","max","apiKeysSlug","collections","map","collection","fields","retention","task","interfaceName","schedule","cron","queue","handler","req","cutoff","Date","now","days","toISOString","result","frogbot","find","where","requestedAt","less_than","limit","sort","depth","overrideAccess","docs","length","doc","delete","blobKey","id","output","undefined","cli","commands","access","jobs","tasks","beforeOperation","beforeUpstream","afterUpstream","afterError","aiCapturePlugin","isInteger","storageRoot"],"mappings":"AAAA,SAASA,YAAY,EAAcC,aAAa,QAAsC,UAAU;AAEhG,SAASC,wBAAwB,QAAQ,kBAAkB;AAC3D,SAASC,qBAAqB,QAAQ,+BAA+B;AACrE,SAASC,yBAAyB,QAAQ,mCAAmC;AAC7E,SAASC,kBAAkB,QAAQ,aAAa;AAChD,SAASC,wBAAwB,QAAQ,0BAA0B;AAGnE,SAASC,aAAa,EAAEC,aAAa,QAAQ,YAAY;AACzD,SAASN,wBAAwB,QAAQ,kBAAkB;AAC3D,SAASI,wBAAwB,QAAQ,0BAA0B;AACnE,SAASG,kBAAkB,QAAQ,mCAAmC;AAmBtE,SAASC,aAAaC,KAAa,EAAEC,IAAY;IAC/C,IAAI,CAACC,OAAOC,QAAQ,CAACH,UAAUA,QAAQ,KAAKA,QAAQ,GAAG;QACrD,MAAM,IAAII,MAAM,CAAC,oBAAoB,EAAEH,KAAK,yBAAyB,CAAC;IACxE;AACF;AAEA,MAAMI,YAAYhB,aAAqC;IACrDiB,MAAM;IACNC,OAAO;IACPC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAE;QACnC,IAAI,CAACF,OAAOG,EAAE,EAAE,MAAM,IAAIR,MAAM;QAEhC,MAAM,EAAES,cAAc,EAAEC,OAAO,EAAE,GAAGJ;QACpC,MAAMK,QAAQrB,mBAAmB;YAC/BsB,SAASN,QAAQM,OAAO,IAAI;YAC5BC,YAAYP,QAAQO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AAEA,OAAO,SAASC,gBAAgB3D,UAAkC,CAAC,CAAC;IAClE,MAAMO,aAAaP,QAAQO,UAAU,IAAI;IACzC,MAAMC,eAAeR,QAAQQ,YAAY,IAAI,KAAK,OAAO;IACzDnB,aAAakB,YAAY;IACzB,IAAI,CAACf,OAAOoE,SAAS,CAACpD,iBAAiBA,eAAe,GAAG;QACvD,MAAM,IAAId,MAAM;IAClB;IAEA,IACEM,QAAQmB,SAAS,IAChB,CAAA,CAAC3B,OAAOoE,SAAS,CAAC5D,QAAQmB,SAAS,CAACW,IAAI,KAAK9B,QAAQmB,SAAS,CAACW,IAAI,GAAG,CAAA,GACvE;QACA,MAAM,IAAIpC,MAAM;IAClB;IAEA,OAAOC,UAAU;QACf,GAAGK,OAAO;QACVG,gBAAgBH,QAAQG,cAAc,IAAI;QAC1CI;QACAC;QACAJ,SAASJ,QAAQI,OAAO,IAAInB,yBAAyBe,QAAQ6D,WAAW;IAC1E;AACF","file":"index.js"}
@@ -0,0 +1,3 @@
1
+ import type { CaptureStorage } from '../types.js';
2
+ export declare function filesystemCaptureStorage(root?: string): CaptureStorage;
3
+ //# sourceMappingURL=filesystem.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filesystem.d.ts","sourceRoot":"","sources":["../../src/storage/filesystem.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD,wBAAgB,wBAAwB,CAAC,IAAI,SAAsB,GAAG,cAAc,CA8BnF"}
@@ -0,0 +1,38 @@
1
+ import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ export function filesystemCaptureStorage(root = '.frogbot/captures') {
4
+ const resolve = (key)=>{
5
+ const target = path.resolve(root, key);
6
+ const base = `${path.resolve(root)}${path.sep}`;
7
+ if (!target.startsWith(base)) throw new Error('Invalid capture key');
8
+ return target;
9
+ };
10
+ return {
11
+ async put (key, bytes) {
12
+ const target = resolve(key);
13
+ await mkdir(path.dirname(target), {
14
+ recursive: true
15
+ });
16
+ await writeFile(target, bytes);
17
+ },
18
+ async get (key) {
19
+ return readFile(resolve(key));
20
+ },
21
+ async delete (key) {
22
+ await rm(resolve(key), {
23
+ force: true
24
+ });
25
+ },
26
+ async *list (prefix) {
27
+ const directory = resolve(prefix || '.');
28
+ for (const entry of (await readdir(directory, {
29
+ recursive: true
30
+ }).catch(()=>[]))){
31
+ const key = path.posix.join(prefix, String(entry).split(path.sep).join('/'));
32
+ if (key.endsWith('.json.gz')) yield key;
33
+ }
34
+ }
35
+ };
36
+ }
37
+
38
+ //# sourceMappingURL=filesystem.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/storage/filesystem.ts"],"names":["mkdir","readdir","readFile","rm","writeFile","path","filesystemCaptureStorage","root","resolve","key","target","base","sep","startsWith","Error","put","bytes","dirname","recursive","get","delete","force","list","prefix","directory","entry","catch","posix","join","String","split","endsWith"],"mappings":"AAAA,SAASA,KAAK,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,EAAE,EAAEC,SAAS,QAAQ,mBAAmB;AAC3E,OAAOC,UAAU,YAAY;AAI7B,OAAO,SAASC,yBAAyBC,OAAO,mBAAmB;IACjE,MAAMC,UAAU,CAACC;QACf,MAAMC,SAASL,KAAKG,OAAO,CAACD,MAAME;QAClC,MAAME,OAAO,GAAGN,KAAKG,OAAO,CAACD,QAAQF,KAAKO,GAAG,EAAE;QAC/C,IAAI,CAACF,OAAOG,UAAU,CAACF,OAAO,MAAM,IAAIG,MAAM;QAE9C,OAAOJ;IACT;IAEA,OAAO;QACL,MAAMK,KAAIN,GAAG,EAAEO,KAAK;YAClB,MAAMN,SAASF,QAAQC;YACvB,MAAMT,MAAMK,KAAKY,OAAO,CAACP,SAAS;gBAAEQ,WAAW;YAAK;YACpD,MAAMd,UAAUM,QAAQM;QAC1B;QACA,MAAMG,KAAIV,GAAG;YACX,OAAOP,SAASM,QAAQC;QAC1B;QACA,MAAMW,QAAOX,GAAG;YACd,MAAMN,GAAGK,QAAQC,MAAM;gBAAEY,OAAO;YAAK;QACvC;QACA,OAAOC,MAAKC,MAAM;YAChB,MAAMC,YAAYhB,QAAQe,UAAU;YAEpC,KAAK,MAAME,SAAS,CAAA,MAAMxB,QAAQuB,WAAW;gBAAEN,WAAW;YAAK,GAAGQ,KAAK,CAAC,IAAM,EAAE,CAAA,EAAG;gBACjF,MAAMjB,MAAMJ,KAAKsB,KAAK,CAACC,IAAI,CAACL,QAAQM,OAAOJ,OAAOK,KAAK,CAACzB,KAAKO,GAAG,EAAEgB,IAAI,CAAC;gBACvE,IAAInB,IAAIsB,QAAQ,CAAC,aAAa,MAAMtB;YACtC;QACF;IACF;AACF","file":"filesystem.js"}
@@ -0,0 +1,3 @@
1
+ import type { TrainingDataRecord } from './types.js';
2
+ export declare function encodeTrainingData(records: AsyncIterable<TrainingDataRecord>): ReadableStream<Uint8Array>;
3
+ //# sourceMappingURL=encodeTrainingData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encodeTrainingData.d.ts","sourceRoot":"","sources":["../../src/training/encodeTrainingData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAmBrD,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,aAAa,CAAC,kBAAkB,CAAC,GACzC,cAAc,CAAC,UAAU,CAAC,CAiB5B"}
@@ -0,0 +1,30 @@
1
+ const encoder = new TextEncoder();
2
+ async function* encodeRecords(records) {
3
+ for await (const record of records){
4
+ yield encoder.encode(`{"chat":${JSON.stringify(record.chat)},"messages":[`);
5
+ for(let index = 0; index < record.messages.length; index += 1){
6
+ if (index > 0) yield encoder.encode(',');
7
+ yield encoder.encode(JSON.stringify(record.messages[index]));
8
+ }
9
+ yield encoder.encode(']}\n');
10
+ }
11
+ }
12
+ export function encodeTrainingData(records) {
13
+ const chunks = encodeRecords(records);
14
+ return new ReadableStream({
15
+ async cancel () {
16
+ await chunks.return(undefined);
17
+ },
18
+ async pull (controller) {
19
+ try {
20
+ const chunk = await chunks.next();
21
+ if (chunk.done) controller.close();
22
+ else controller.enqueue(chunk.value);
23
+ } catch (error) {
24
+ controller.error(error);
25
+ }
26
+ }
27
+ });
28
+ }
29
+
30
+ //# sourceMappingURL=encodeTrainingData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/training/encodeTrainingData.ts"],"names":["encoder","TextEncoder","encodeRecords","records","record","encode","JSON","stringify","chat","index","messages","length","encodeTrainingData","chunks","ReadableStream","cancel","return","undefined","pull","controller","chunk","next","done","close","enqueue","value","error"],"mappings":"AAEA,MAAMA,UAAU,IAAIC;AAEpB,gBAAgBC,cACdC,OAA0C;IAE1C,WAAW,MAAMC,UAAUD,QAAS;QAClC,MAAMH,QAAQK,MAAM,CAAC,CAAC,QAAQ,EAAEC,KAAKC,SAAS,CAACH,OAAOI,IAAI,EAAE,aAAa,CAAC;QAE1E,IAAK,IAAIC,QAAQ,GAAGA,QAAQL,OAAOM,QAAQ,CAACC,MAAM,EAAEF,SAAS,EAAG;YAC9D,IAAIA,QAAQ,GAAG,MAAMT,QAAQK,MAAM,CAAC;YACpC,MAAML,QAAQK,MAAM,CAACC,KAAKC,SAAS,CAACH,OAAOM,QAAQ,CAACD,MAAM;QAC5D;QAEA,MAAMT,QAAQK,MAAM,CAAC;IACvB;AACF;AAEA,OAAO,SAASO,mBACdT,OAA0C;IAE1C,MAAMU,SAASX,cAAcC;IAE7B,OAAO,IAAIW,eAAe;QACxB,MAAMC;YACJ,MAAMF,OAAOG,MAAM,CAACC;QACtB;QACA,MAAMC,MAAKC,UAAU;YACnB,IAAI;gBACF,MAAMC,QAAQ,MAAMP,OAAOQ,IAAI;gBAC/B,IAAID,MAAME,IAAI,EAAEH,WAAWI,KAAK;qBAC3BJ,WAAWK,OAAO,CAACJ,MAAMK,KAAK;YACrC,EAAE,OAAOC,OAAO;gBACdP,WAAWO,KAAK,CAACA;YACnB;QACF;IACF;AACF","file":"encodeTrainingData.js"}
@@ -0,0 +1,4 @@
1
+ import type { FrogBot } from 'frogbot';
2
+ import type { ReadTrainingDataOptions } from './types.js';
3
+ export declare function exportTrainingData(frogbot: FrogBot, options?: ReadTrainingDataOptions): ReadableStream<Uint8Array>;
4
+ //# sourceMappingURL=exportTrainingData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exportTrainingData.d.ts","sourceRoot":"","sources":["../../src/training/exportTrainingData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAIvC,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAE1D,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,uBAA4B,GACpC,cAAc,CAAC,UAAU,CAAC,CAE5B"}
@@ -0,0 +1,7 @@
1
+ import { encodeTrainingData } from './encodeTrainingData.js';
2
+ import { readTrainingData } from './readTrainingData.js';
3
+ export function exportTrainingData(frogbot, options = {}) {
4
+ return encodeTrainingData(readTrainingData(frogbot, options));
5
+ }
6
+
7
+ //# sourceMappingURL=exportTrainingData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/training/exportTrainingData.ts"],"names":["encodeTrainingData","readTrainingData","exportTrainingData","frogbot","options"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,0BAA0B;AAC7D,SAASC,gBAAgB,QAAQ,wBAAwB;AAGzD,OAAO,SAASC,mBACdC,OAAgB,EAChBC,UAAmC,CAAC,CAAC;IAErC,OAAOJ,mBAAmBC,iBAAiBE,SAASC;AACtD","file":"exportTrainingData.js"}
@@ -0,0 +1,4 @@
1
+ import type { FrogBot } from 'frogbot';
2
+ import type { ReadTrainingDataOptions, TrainingDataRecord } from './types.js';
3
+ export declare function readTrainingData(frogbot: FrogBot, options?: ReadTrainingDataOptions): AsyncGenerator<TrainingDataRecord>;
4
+ //# sourceMappingURL=readTrainingData.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readTrainingData.d.ts","sourceRoot":"","sources":["../../src/training/readTrainingData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,KAAK,EAAE,uBAAuB,EAAwB,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAIpG,wBAAuB,gBAAgB,CACrC,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,uBAA4B,GACpC,cAAc,CAAC,kBAAkB,CAAC,CAoDpC"}
@@ -0,0 +1,60 @@
1
+ const DEFAULT_PAGE_SIZE = 100;
2
+ export async function* readTrainingData(frogbot, options = {}) {
3
+ if (!frogbot.config.chat.enabled) {
4
+ throw new Error('Training data export requires chat persistence.');
5
+ }
6
+ const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
7
+ if (!Number.isInteger(pageSize) || pageSize < 1) {
8
+ throw new Error('Training data export pageSize must be a positive integer.');
9
+ }
10
+ const common = {
11
+ depth: 0,
12
+ limit: pageSize,
13
+ overrideAccess: options.overrideAccess ?? false,
14
+ req: options.req
15
+ };
16
+ let chatPage = 1;
17
+ while(true){
18
+ const chats = await frogbot.find({
19
+ ...common,
20
+ collection: frogbot.config.chat.chatsSlug,
21
+ page: chatPage,
22
+ sort: [
23
+ 'createdAt',
24
+ 'id'
25
+ ],
26
+ where: options.where
27
+ });
28
+ for (const chat of chats.docs){
29
+ const messages = [];
30
+ let messagePage = 1;
31
+ while(true){
32
+ const result = await frogbot.find({
33
+ ...common,
34
+ collection: frogbot.config.chat.messagesSlug,
35
+ page: messagePage,
36
+ sort: [
37
+ 'createdAt',
38
+ 'id'
39
+ ],
40
+ where: {
41
+ chat: {
42
+ equals: chat.id
43
+ }
44
+ }
45
+ });
46
+ messages.push(...result.docs);
47
+ if (!result.hasNextPage) break;
48
+ messagePage += 1;
49
+ }
50
+ yield {
51
+ chat,
52
+ messages
53
+ };
54
+ }
55
+ if (!chats.hasNextPage) break;
56
+ chatPage += 1;
57
+ }
58
+ }
59
+
60
+ //# sourceMappingURL=readTrainingData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/training/readTrainingData.ts"],"names":["DEFAULT_PAGE_SIZE","readTrainingData","frogbot","options","config","chat","enabled","Error","pageSize","Number","isInteger","common","depth","limit","overrideAccess","req","chatPage","chats","find","collection","chatsSlug","page","sort","where","docs","messages","messagePage","result","messagesSlug","equals","id","push","hasNextPage"],"mappings":"AAIA,MAAMA,oBAAoB;AAE1B,OAAO,gBAAgBC,iBACrBC,OAAgB,EAChBC,UAAmC,CAAC,CAAC;IAErC,IAAI,CAACD,QAAQE,MAAM,CAACC,IAAI,CAACC,OAAO,EAAE;QAChC,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,WAAWL,QAAQK,QAAQ,IAAIR;IACrC,IAAI,CAACS,OAAOC,SAAS,CAACF,aAAaA,WAAW,GAAG;QAC/C,MAAM,IAAID,MAAM;IAClB;IAEA,MAAMI,SAAS;QACbC,OAAO;QACPC,OAAOL;QACPM,gBAAgBX,QAAQW,cAAc,IAAI;QAC1CC,KAAKZ,QAAQY,GAAG;IAClB;IAEA,IAAIC,WAAW;IAEf,MAAO,KAAM;QACX,MAAMC,QAAQ,MAAMf,QAAQgB,IAAI,CAAC;YAC/B,GAAGP,MAAM;YACTQ,YAAYjB,QAAQE,MAAM,CAACC,IAAI,CAACe,SAAS;YACzCC,MAAML;YACNM,MAAM;gBAAC;gBAAa;aAAK;YACzBC,OAAOpB,QAAQoB,KAAK;QACtB;QAEA,KAAK,MAAMlB,QAAQY,MAAMO,IAAI,CAAE;YAC7B,MAAMC,WAAmC,EAAE;YAC3C,IAAIC,cAAc;YAElB,MAAO,KAAM;gBACX,MAAMC,SAAS,MAAMzB,QAAQgB,IAAI,CAAC;oBAChC,GAAGP,MAAM;oBACTQ,YAAYjB,QAAQE,MAAM,CAACC,IAAI,CAACuB,YAAY;oBAC5CP,MAAMK;oBACNJ,MAAM;wBAAC;wBAAa;qBAAK;oBACzBC,OAAO;wBAAElB,MAAM;4BAAEwB,QAAQxB,KAAKyB,EAAE;wBAAC;oBAAE;gBACrC;gBAEAL,SAASM,IAAI,IAAIJ,OAAOH,IAAI;gBAC5B,IAAI,CAACG,OAAOK,WAAW,EAAE;gBACzBN,eAAe;YACjB;YAEA,MAAM;gBAAErB;gBAAMoB;YAAS;QACzB;QAEA,IAAI,CAACR,MAAMe,WAAW,EAAE;QACxBhB,YAAY;IACd;AACF","file":"readTrainingData.js"}
@@ -0,0 +1,13 @@
1
+ import type { FrogBotRequest, Where } from 'frogbot';
2
+ export type TrainingDataDocument = Record<string, unknown>;
3
+ export type TrainingDataRecord = {
4
+ chat: TrainingDataDocument;
5
+ messages: TrainingDataDocument[];
6
+ };
7
+ export type ReadTrainingDataOptions = {
8
+ where?: Where;
9
+ pageSize?: number;
10
+ req?: FrogBotRequest;
11
+ overrideAccess?: boolean;
12
+ };
13
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/training/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErD,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE3D,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,oBAAoB,CAAC;IAC3B,QAAQ,EAAE,oBAAoB,EAAE,CAAC;CAClC,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACpC,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,cAAc,CAAC;IACrB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { };
2
+
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/training/types.ts"],"names":[],"mappings":"AASA,WAKE","file":"types.js"}
@@ -0,0 +1,43 @@
1
+ import type { Access } from 'frogbot';
2
+ export type CaptureStorage = {
3
+ put(key: string, bytes: Uint8Array): Promise<void>;
4
+ get(key: string): Promise<Uint8Array>;
5
+ delete(key: string): Promise<void>;
6
+ list(prefix: string): AsyncIterable<string>;
7
+ };
8
+ export type CaptureRecord = {
9
+ captureId: string;
10
+ requestId: string;
11
+ operation: 'chat.completions' | 'messages' | 'responses';
12
+ model: string;
13
+ provider: string;
14
+ requestedAt: string;
15
+ completedAt: string;
16
+ user?: string | number;
17
+ apiKey?: string;
18
+ request: {
19
+ messages?: unknown[];
20
+ system?: unknown;
21
+ tools?: Record<string, unknown>;
22
+ params?: Record<string, unknown>;
23
+ };
24
+ response?: unknown;
25
+ error?: {
26
+ name?: string;
27
+ message: string;
28
+ };
29
+ };
30
+ export type AICapturePluginOptions = {
31
+ enabled?: boolean;
32
+ storage?: CaptureStorage;
33
+ storageRoot?: string;
34
+ retention?: false | {
35
+ days: number;
36
+ cron?: string;
37
+ };
38
+ sampleRate?: number;
39
+ maxBodyBytes?: number;
40
+ collectionSlug?: string;
41
+ access?: Access;
42
+ };
43
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEtC,MAAM,MAAM,cAAc,GAAG;IAC3B,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACtC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,CAAC,M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.js ADDED
@@ -0,0 +1,3 @@
1
+ export { };
2
+
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts"],"names":[],"mappings":"AA6BA,WASE","file":"types.js"}
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@frogbotai/plugin-ai-capture",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.43.0",
4
+ "description": "Blob-first AI request capture for FrogBot.",
5
+ "license": "MIT",
6
+ "author": "Colby Gilbert",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/frogbotai/frogbot.git",
10
+ "directory": "packages/plugins/plugin-ai-capture"
11
+ },
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "sideEffects": false,
26
+ "engines": {
27
+ "node": ">=24.22.3"
28
+ },
29
+ "peerDependencies": {
30
+ "frogbot": "0.43.0"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "24.12.3",
34
+ "typescript": "6.0.3",
35
+ "vitest": "4.1.2",
36
+ "frogbot": "0.43.0"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "build": "node ../../../scripts/build-package.mjs",
43
+ "clean": "rm -rf dist",
44
+ "typecheck": "tsc --noEmit"
45
+ }
6
46
  }