@dnotifier-realtime/dnotifier 1.1.7 → 1.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -0
- package/dist/cjs/dnotifier.js +1 -1
- package/dist/cjs/providers/openai.js +1 -1
- package/dist/cjs/transport/httpTransport.js +1 -1
- package/dist/cjs/transport/websocketTransport.js +1 -1
- package/dist/cjs/utils/buffer.js +1 -1
- package/dist/cjs/utils/frame.js +1 -1
- package/dist/cjs/utils/id.js +1 -1
- package/dist/cjs/utils/payload.js +1 -1
- package/dist/config/endpoints.d.ts +20 -0
- package/dist/config/endpoints.d.ts.map +1 -0
- package/dist/config/endpoints.js +1 -0
- package/dist/dnotifier.cjs +1105 -70
- package/dist/dnotifier.d.ts +29 -3
- package/dist/dnotifier.d.ts.map +1 -1
- package/dist/dnotifier.js +1 -1
- package/dist/providers/openai.js +1 -1
- package/dist/transport/httpTransport.d.ts +3 -1
- package/dist/transport/httpTransport.d.ts.map +1 -1
- package/dist/transport/httpTransport.js +1 -1
- package/dist/transport/websocketTransport.js +1 -1
- package/dist/utils/buffer.js +1 -1
- package/dist/utils/frame.js +1 -1
- package/dist/utils/id.js +1 -1
- package/dist/utils/logs.d.ts +28 -0
- package/dist/utils/logs.d.ts.map +1 -0
- package/dist/utils/logs.js +1 -0
- package/dist/utils/payload.js +1 -1
- package/dist/workflow/agent.d.ts +13 -0
- package/dist/workflow/agent.d.ts.map +1 -0
- package/dist/workflow/agent.js +1 -0
- package/dist/workflow/context.d.ts +54 -0
- package/dist/workflow/context.d.ts.map +1 -0
- package/dist/workflow/context.js +1 -0
- package/dist/workflow/errors.d.ts +9 -0
- package/dist/workflow/errors.d.ts.map +1 -0
- package/dist/workflow/errors.js +1 -0
- package/dist/workflow/ids.d.ts +3 -0
- package/dist/workflow/ids.d.ts.map +1 -0
- package/dist/workflow/ids.js +1 -0
- package/dist/workflow/index.d.ts +6 -0
- package/dist/workflow/index.d.ts.map +1 -0
- package/dist/workflow/index.js +1 -0
- package/dist/workflow/jsonPayload.d.ts +3 -0
- package/dist/workflow/jsonPayload.d.ts.map +1 -0
- package/dist/workflow/jsonPayload.js +1 -0
- package/dist/workflow/mockObservabilityClient.d.ts +47 -0
- package/dist/workflow/mockObservabilityClient.d.ts.map +1 -0
- package/dist/workflow/mockObservabilityClient.js +1 -0
- package/dist/workflow/observability.d.ts +35 -0
- package/dist/workflow/observability.d.ts.map +1 -0
- package/dist/workflow/observability.js +1 -0
- package/dist/workflow/runner.d.ts +17 -0
- package/dist/workflow/runner.d.ts.map +1 -0
- package/dist/workflow/runner.js +1 -0
- package/dist/workflow/stepTypes.d.ts +25 -0
- package/dist/workflow/stepTypes.d.ts.map +1 -0
- package/dist/workflow/stepTypes.js +1 -0
- package/dist/workflow/workflow.d.ts +18 -0
- package/dist/workflow/workflow.d.ts.map +1 -0
- package/dist/workflow/workflow.js +1 -0
- package/dist/workflow/workflowObservabilityClient.d.ts +41 -0
- package/dist/workflow/workflowObservabilityClient.d.ts.map +1 -0
- package/dist/workflow/workflowObservabilityClient.js +1 -0
- package/package.json +1 -1
package/dist/dnotifier.cjs
CHANGED
|
@@ -30,7 +30,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/dnotifier.js
|
|
31
31
|
var dnotifier_exports = {};
|
|
32
32
|
__export(dnotifier_exports, {
|
|
33
|
-
|
|
33
|
+
Agent: () => Agent,
|
|
34
|
+
DNotifier: () => DNotifier,
|
|
35
|
+
Workflow: () => Workflow,
|
|
36
|
+
WorkflowContext: () => WorkflowContext,
|
|
37
|
+
WorkflowError: () => WorkflowError,
|
|
38
|
+
WorkflowRunner: () => WorkflowRunner,
|
|
39
|
+
defineAgent: () => defineAgent
|
|
34
40
|
});
|
|
35
41
|
module.exports = __toCommonJS(dnotifier_exports);
|
|
36
42
|
|
|
@@ -42,14 +48,16 @@ var HttpTransport = class {
|
|
|
42
48
|
// this.appSecret = secret;
|
|
43
49
|
// this.userId = userId;
|
|
44
50
|
// }
|
|
45
|
-
constructor({ url }) {
|
|
51
|
+
constructor({ url, headers = {} }) {
|
|
46
52
|
this.url = url;
|
|
53
|
+
this.headers = headers;
|
|
47
54
|
}
|
|
48
55
|
async send(payload) {
|
|
49
56
|
const res = await fetch(`${this.url}`, {
|
|
50
57
|
method: "POST",
|
|
51
58
|
headers: {
|
|
52
|
-
"Content-Type": "application/json"
|
|
59
|
+
"Content-Type": "application/json",
|
|
60
|
+
...this.headers
|
|
53
61
|
},
|
|
54
62
|
body: JSON.stringify(payload)
|
|
55
63
|
});
|
|
@@ -214,6 +222,34 @@ var WebsocketTransport = class extends import_events.default {
|
|
|
214
222
|
}
|
|
215
223
|
};
|
|
216
224
|
|
|
225
|
+
// src/config/endpoints.js
|
|
226
|
+
var baseHost = "https://dev.api.dnotifier.com";
|
|
227
|
+
var wsHost = baseHost.replace(/^http/, "ws");
|
|
228
|
+
var logHost = `${baseHost}/ecs`;
|
|
229
|
+
var workflowSdkBase = `${logHost}/api/v1/log/sdk/workflow`;
|
|
230
|
+
var DNotifierEndpoints = {
|
|
231
|
+
// Change this host to switch all SDK endpoints.
|
|
232
|
+
baseHost,
|
|
233
|
+
// Core realtime/auth endpoints.
|
|
234
|
+
wsUrl: `${wsHost}/ecs/ws`,
|
|
235
|
+
rpcSendUrl: `${baseHost}/rpc/v1/message/send`,
|
|
236
|
+
authUrl: `${baseHost}/ecs/api/v1/sdk/auth`,
|
|
237
|
+
// SDK log endpoints.
|
|
238
|
+
logHost,
|
|
239
|
+
addLogUrl: `${logHost}/api/v1/log/sdk/add-log`,
|
|
240
|
+
updateLogStatusUrl: `${logHost}/api/v1/log/sdk/update-log-status`,
|
|
241
|
+
addSessionStepUrl: `${logHost}/api/v1/log/sdk/add-session-step`,
|
|
242
|
+
// Workflow observability (SDK ingest).
|
|
243
|
+
workflowRegisterUrl: `${workflowSdkBase}/workflows`,
|
|
244
|
+
workflowExecutionsUrl: `${workflowSdkBase}/executions`,
|
|
245
|
+
workflowStepsUrl: `${workflowSdkBase}/steps`,
|
|
246
|
+
workflowExecutionUrl: (executionId) => `${workflowSdkBase}/executions/${executionId}`,
|
|
247
|
+
workflowExecutionCompleteUrl: (executionId) => `${workflowSdkBase}/executions/${executionId}/complete`,
|
|
248
|
+
workflowExecutionStepsUrl: (executionId) => `${workflowSdkBase}/executions/${executionId}/steps`
|
|
249
|
+
// wsUrl:`ws://localhost:7072`,
|
|
250
|
+
// rpcSendUrl:`http://localhost:8081/rpc/v1/message/send`,
|
|
251
|
+
};
|
|
252
|
+
|
|
217
253
|
// src/utils/id.js
|
|
218
254
|
var prefixId = (appId, id) => {
|
|
219
255
|
if (id.includes(":")) return id;
|
|
@@ -281,8 +317,897 @@ function toUint8(data) {
|
|
|
281
317
|
return new TextEncoder().encode(data);
|
|
282
318
|
}
|
|
283
319
|
|
|
284
|
-
// src/
|
|
320
|
+
// src/utils/logs.js
|
|
321
|
+
var host = DNotifierEndpoints.logHost;
|
|
322
|
+
var DEFAULT_LOG_URL = DNotifierEndpoints.addLogUrl;
|
|
323
|
+
var DEFAULT_UPDATE_LOG_URL = DNotifierEndpoints.updateLogStatusUrl;
|
|
324
|
+
var DEFAULT_SESSION_STEP_URL = DNotifierEndpoints.addSessionStepUrl;
|
|
325
|
+
var sessionStepTracker = /* @__PURE__ */ new Map();
|
|
326
|
+
var LogsClient = class {
|
|
327
|
+
constructor({ enabled = false, appId = null, token = null, model = null } = {}) {
|
|
328
|
+
this.enabled = Boolean(enabled);
|
|
329
|
+
this.appId = appId;
|
|
330
|
+
this.token = token;
|
|
331
|
+
this.model = model;
|
|
332
|
+
}
|
|
333
|
+
configure({ enabled, appId, token, model } = {}) {
|
|
334
|
+
if (enabled !== void 0) this.enabled = Boolean(enabled);
|
|
335
|
+
if (appId !== void 0) this.appId = appId;
|
|
336
|
+
if (token !== void 0) this.token = token;
|
|
337
|
+
if (model !== void 0) this.model = model;
|
|
338
|
+
}
|
|
339
|
+
_transport(url) {
|
|
340
|
+
const headers = this.token ? { authorization: `${this.token}` } : {};
|
|
341
|
+
return new HttpTransport({ url, headers });
|
|
342
|
+
}
|
|
343
|
+
async createLog(payload) {
|
|
344
|
+
return await this._transport(DEFAULT_LOG_URL).send(payload);
|
|
345
|
+
}
|
|
346
|
+
async updateLog(payload) {
|
|
347
|
+
return await this._transport(DEFAULT_UPDATE_LOG_URL).send(payload);
|
|
348
|
+
}
|
|
349
|
+
async addSessionStepLog(payload) {
|
|
350
|
+
return await this._transport(DEFAULT_SESSION_STEP_URL).send(payload);
|
|
351
|
+
}
|
|
352
|
+
async startAiLogging({ sessionId, prompts, isExistingSession = false }) {
|
|
353
|
+
if (!this.enabled) return;
|
|
354
|
+
if (!this.token || !this.appId || !sessionId) return;
|
|
355
|
+
const createdDate = (/* @__PURE__ */ new Date()).toISOString();
|
|
356
|
+
if (isExistingSession) {
|
|
357
|
+
await this.updateLog({
|
|
358
|
+
sessionId,
|
|
359
|
+
status: "InProgress",
|
|
360
|
+
updatedAt: createdDate
|
|
361
|
+
});
|
|
362
|
+
} else {
|
|
363
|
+
await this.createLog({
|
|
364
|
+
appId: this.appId,
|
|
365
|
+
sessionId,
|
|
366
|
+
status: "InProgress",
|
|
367
|
+
model: this.model,
|
|
368
|
+
calls: 1,
|
|
369
|
+
createdDate,
|
|
370
|
+
step: 1
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
sessionStepTracker.set(sessionId, {
|
|
374
|
+
appId: this.appId,
|
|
375
|
+
sessionId,
|
|
376
|
+
tokens: 0,
|
|
377
|
+
status: "InProgress",
|
|
378
|
+
prompts,
|
|
379
|
+
createdDate
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
async completeAiLogging({ sessionId, response = null }) {
|
|
383
|
+
if (!this.enabled) return;
|
|
384
|
+
if (!this.token || !sessionId) return;
|
|
385
|
+
const pendingStepLog = sessionStepTracker.get(sessionId);
|
|
386
|
+
if (!pendingStepLog) return;
|
|
387
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
388
|
+
await this.updateLog({
|
|
389
|
+
sessionId,
|
|
390
|
+
status: "Completed",
|
|
391
|
+
updatedAt
|
|
392
|
+
});
|
|
393
|
+
sessionStepTracker.delete(sessionId);
|
|
394
|
+
const stepInput = JSON.stringify(pendingStepLog.prompts ?? null);
|
|
395
|
+
const stepOutput = JSON.stringify(response ?? null);
|
|
396
|
+
const prompts = [stepInput, stepOutput];
|
|
397
|
+
await this.addSessionStepLog({
|
|
398
|
+
...pendingStepLog,
|
|
399
|
+
prompts,
|
|
400
|
+
response: stepOutput,
|
|
401
|
+
status: "Completed",
|
|
402
|
+
updatedAt,
|
|
403
|
+
tokens: response?.data?.usage?.total_tokens ?? 0
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
// src/workflow/errors.js
|
|
409
|
+
var WorkflowError = class extends Error {
|
|
410
|
+
/**
|
|
411
|
+
* @param {string} message
|
|
412
|
+
* @param {{ agentName?: string, cause?: Error }} [options]
|
|
413
|
+
*/
|
|
414
|
+
constructor(message, options = {}) {
|
|
415
|
+
super(message);
|
|
416
|
+
this.name = "WorkflowError";
|
|
417
|
+
this.agentName = options.agentName;
|
|
418
|
+
if (options.cause) {
|
|
419
|
+
this.cause = options.cause;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
// src/workflow/agent.js
|
|
425
|
+
var Agent = class {
|
|
426
|
+
/**
|
|
427
|
+
* @param {{ name: string, run: (ctx: import("./context.js").WorkflowContext) => Promise<*> }} config
|
|
428
|
+
*/
|
|
429
|
+
constructor({ name, run }) {
|
|
430
|
+
if (!name || typeof name !== "string") {
|
|
431
|
+
throw new WorkflowError("Agent name is required");
|
|
432
|
+
}
|
|
433
|
+
if (typeof run !== "function") {
|
|
434
|
+
throw new WorkflowError(`Agent "${name}": run must be a function`);
|
|
435
|
+
}
|
|
436
|
+
this.name = name;
|
|
437
|
+
this.run = run;
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
function defineAgent(config) {
|
|
441
|
+
return new Agent(config);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/workflow/workflow.js
|
|
445
|
+
function normalizeDescription(description) {
|
|
446
|
+
if (description === void 0 || description === null || description === "") {
|
|
447
|
+
return void 0;
|
|
448
|
+
}
|
|
449
|
+
if (typeof description !== "string") {
|
|
450
|
+
throw new WorkflowError("Workflow description must be a string");
|
|
451
|
+
}
|
|
452
|
+
const trimmed = description.trim();
|
|
453
|
+
if (trimmed.length > 100) {
|
|
454
|
+
throw new WorkflowError("Workflow description must be at most 100 characters");
|
|
455
|
+
}
|
|
456
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
457
|
+
}
|
|
458
|
+
var Workflow = class {
|
|
459
|
+
/**
|
|
460
|
+
* @param {{
|
|
461
|
+
* name: string,
|
|
462
|
+
* description?: string,
|
|
463
|
+
* observability?: boolean,
|
|
464
|
+
* entry: (ctx: import("./context.js").WorkflowContext) => Promise<*>,
|
|
465
|
+
* }} options
|
|
466
|
+
*/
|
|
467
|
+
constructor({ name, description, observability = false, entry }) {
|
|
468
|
+
if (!name || typeof name !== "string") {
|
|
469
|
+
throw new WorkflowError("Workflow name is required");
|
|
470
|
+
}
|
|
471
|
+
if (typeof entry !== "function") {
|
|
472
|
+
throw new WorkflowError("Workflow entry must be a function");
|
|
473
|
+
}
|
|
474
|
+
this.name = name.trim();
|
|
475
|
+
this.description = normalizeDescription(description);
|
|
476
|
+
this.observability = Boolean(observability);
|
|
477
|
+
this.entry = entry;
|
|
478
|
+
this._agents = /* @__PURE__ */ new Map();
|
|
479
|
+
this._registeredWithObservability = false;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* @param {string} name
|
|
483
|
+
* @param {import("./agent.js").Agent} agent
|
|
484
|
+
*/
|
|
485
|
+
registerAgent(name, agent) {
|
|
486
|
+
if (!name || typeof name !== "string") {
|
|
487
|
+
throw new WorkflowError("Agent registration name is required");
|
|
488
|
+
}
|
|
489
|
+
if (!agent || typeof agent.run !== "function") {
|
|
490
|
+
throw new WorkflowError(`Invalid agent for "${name}"`);
|
|
491
|
+
}
|
|
492
|
+
this._agents.set(name, agent);
|
|
493
|
+
return this;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* @param {Record<string, import("./agent.js").Agent>} agents
|
|
497
|
+
*/
|
|
498
|
+
registerAgents(agents) {
|
|
499
|
+
for (const [name, agent] of Object.entries(agents)) {
|
|
500
|
+
this.registerAgent(name, agent);
|
|
501
|
+
}
|
|
502
|
+
return this;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* @param {string} name
|
|
506
|
+
* @returns {import("./agent.js").Agent | undefined}
|
|
507
|
+
*/
|
|
508
|
+
getAgent(name) {
|
|
509
|
+
return this._agents.get(name);
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
// src/workflow/stepTypes.js
|
|
514
|
+
var STEP_TYPE_AGENT = "Agent";
|
|
515
|
+
var STEP_TYPE_CUSTOM = "Custom";
|
|
516
|
+
var SDK_API_STEP_TYPES = [
|
|
517
|
+
"sendAI",
|
|
518
|
+
"fetchAIHistory",
|
|
519
|
+
"search",
|
|
520
|
+
"addDocument",
|
|
521
|
+
"updateDocument",
|
|
522
|
+
"deleteDocument",
|
|
523
|
+
"listDocuments",
|
|
524
|
+
"getDocument"
|
|
525
|
+
];
|
|
526
|
+
var LOG_TYPE_BY_API = {
|
|
527
|
+
sendAI: "AI-LLM",
|
|
528
|
+
fetchAIHistory: "AI History",
|
|
529
|
+
search: "Vector Search",
|
|
530
|
+
semanticSearch: "Vector Search",
|
|
531
|
+
addDocument: "Document Add",
|
|
532
|
+
updateDocument: "Document Update",
|
|
533
|
+
deleteDocument: "Document Delete",
|
|
534
|
+
listDocuments: "Document List",
|
|
535
|
+
getDocument: "Document Get",
|
|
536
|
+
agent: STEP_TYPE_AGENT
|
|
537
|
+
};
|
|
538
|
+
var LEGACY_KIND_TO_API = {
|
|
539
|
+
ai_call: "sendAI",
|
|
540
|
+
vector_call: "search"
|
|
541
|
+
};
|
|
542
|
+
function toLogStepType(apiName) {
|
|
543
|
+
if (apiName == null || String(apiName).trim() === "") {
|
|
544
|
+
return STEP_TYPE_CUSTOM;
|
|
545
|
+
}
|
|
546
|
+
const key = String(apiName);
|
|
547
|
+
if (LOG_TYPE_BY_API[key]) return LOG_TYPE_BY_API[key];
|
|
548
|
+
const lower = key.toLowerCase();
|
|
549
|
+
for (const [api, label] of Object.entries(LOG_TYPE_BY_API)) {
|
|
550
|
+
if (api.toLowerCase() === lower) return label;
|
|
551
|
+
}
|
|
552
|
+
return key;
|
|
553
|
+
}
|
|
554
|
+
function resolveApiName(step) {
|
|
555
|
+
const kind = step?.kind;
|
|
556
|
+
if (kind == null || String(kind).trim() === "") return null;
|
|
557
|
+
const k = String(kind);
|
|
558
|
+
if (LEGACY_KIND_TO_API[k]) return LEGACY_KIND_TO_API[k];
|
|
559
|
+
if (k === "agent" || SDK_API_STEP_TYPES.includes(k) || k === "semanticSearch") {
|
|
560
|
+
return k;
|
|
561
|
+
}
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
function resolveStepType(step) {
|
|
565
|
+
if (step?.type != null && String(step.type).trim() !== "") {
|
|
566
|
+
const t = String(step.type).trim();
|
|
567
|
+
if (Object.values(LOG_TYPE_BY_API).includes(t)) return t;
|
|
568
|
+
return toLogStepType(t);
|
|
569
|
+
}
|
|
570
|
+
const api = resolveApiName(step);
|
|
571
|
+
if (api) return toLogStepType(api);
|
|
572
|
+
return STEP_TYPE_CUSTOM;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/workflow/context.js
|
|
576
|
+
function usageFromResponse(response) {
|
|
577
|
+
const usage = response?.data?.usage ?? response?.usage ?? null;
|
|
578
|
+
if (!usage || typeof usage !== "object") {
|
|
579
|
+
return { tokensIn: 0, tokensOut: 0, model: null };
|
|
580
|
+
}
|
|
581
|
+
const tokensIn = usage.prompt_tokens ?? usage.input_tokens ?? usage.tokensIn ?? 0;
|
|
582
|
+
const tokensOut = usage.completion_tokens ?? usage.output_tokens ?? usage.total_tokens ?? usage.tokensOut ?? 0;
|
|
583
|
+
const model = response?.data?.model ?? usage.model ?? null;
|
|
584
|
+
return { tokensIn, tokensOut, model };
|
|
585
|
+
}
|
|
586
|
+
function snapshot(value) {
|
|
587
|
+
try {
|
|
588
|
+
if (value === void 0) return null;
|
|
589
|
+
return JSON.parse(JSON.stringify(value));
|
|
590
|
+
} catch {
|
|
591
|
+
return String(value);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
function apiInput(opts) {
|
|
595
|
+
if (!opts || typeof opts !== "object") return opts ?? null;
|
|
596
|
+
const { label, ...rest } = opts;
|
|
597
|
+
return Object.keys(rest).length > 0 ? rest : null;
|
|
598
|
+
}
|
|
599
|
+
var WorkflowContext = class _WorkflowContext {
|
|
600
|
+
/**
|
|
601
|
+
* @param {{
|
|
602
|
+
* notifier: import("../dnotifier.js").DNotifier,
|
|
603
|
+
* senderId: string,
|
|
604
|
+
* workflow: import("./workflow.js").Workflow,
|
|
605
|
+
* input: *,
|
|
606
|
+
* state?: object,
|
|
607
|
+
* observability?: import("./observability.js").WorkflowObservability | null,
|
|
608
|
+
* executionId?: string | null,
|
|
609
|
+
* agentName?: string | null,
|
|
610
|
+
* }} options
|
|
611
|
+
*/
|
|
612
|
+
constructor({
|
|
613
|
+
notifier,
|
|
614
|
+
senderId,
|
|
615
|
+
workflow,
|
|
616
|
+
input,
|
|
617
|
+
state = {},
|
|
618
|
+
observability = null,
|
|
619
|
+
executionId = null,
|
|
620
|
+
agentName = null
|
|
621
|
+
}) {
|
|
622
|
+
this.notifier = notifier;
|
|
623
|
+
this.senderId = senderId;
|
|
624
|
+
this.workflow = workflow;
|
|
625
|
+
this.input = input;
|
|
626
|
+
this.state = state;
|
|
627
|
+
this._observability = observability;
|
|
628
|
+
this._executionId = executionId;
|
|
629
|
+
this._observabilityEnabled = Boolean(workflow.observability && observability && executionId);
|
|
630
|
+
this.agentName = agentName;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* @param {string} apiName
|
|
634
|
+
* @param {() => Promise<*>} invoke
|
|
635
|
+
* @param {{ label?: string, input?: *, usesTokens?: boolean }} [meta]
|
|
636
|
+
*/
|
|
637
|
+
async _invokeSdkApi(apiName, invoke, meta = {}) {
|
|
638
|
+
const started = Date.now();
|
|
639
|
+
let status = "ok";
|
|
640
|
+
let output = null;
|
|
641
|
+
let error = null;
|
|
642
|
+
const logType = toLogStepType(apiName);
|
|
643
|
+
try {
|
|
644
|
+
output = await invoke();
|
|
645
|
+
return output;
|
|
646
|
+
} catch (err) {
|
|
647
|
+
status = "error";
|
|
648
|
+
error = { message: err?.message ?? String(err), stack: err?.stack };
|
|
649
|
+
throw err;
|
|
650
|
+
} finally {
|
|
651
|
+
if (this._observabilityEnabled) {
|
|
652
|
+
const usage = meta.usesTokens ? usageFromResponse(output) : { tokensIn: 0, tokensOut: 0, model: null };
|
|
653
|
+
const stepKind = this.agentName ?? apiName;
|
|
654
|
+
console.log("[WorkflowContext] recordStep kind:", {
|
|
655
|
+
kind: stepKind,
|
|
656
|
+
agentName: this.agentName,
|
|
657
|
+
apiName,
|
|
658
|
+
type: logType
|
|
659
|
+
});
|
|
660
|
+
await this._observability.recordStep(this._executionId, {
|
|
661
|
+
apiName,
|
|
662
|
+
agentName: this.agentName,
|
|
663
|
+
kind: stepKind,
|
|
664
|
+
type: logType,
|
|
665
|
+
label: meta.label ?? logType,
|
|
666
|
+
status,
|
|
667
|
+
latencyMs: Date.now() - started,
|
|
668
|
+
...usage,
|
|
669
|
+
input: snapshot(meta.input),
|
|
670
|
+
output: snapshot(output),
|
|
671
|
+
error
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* @param {string} name
|
|
678
|
+
* @param {{ input?: * }} [options]
|
|
679
|
+
*/
|
|
680
|
+
async runAgent(name, options = {}) {
|
|
681
|
+
const agent = this.workflow.getAgent(name);
|
|
682
|
+
if (!agent) {
|
|
683
|
+
throw new WorkflowError(`Agent not found: ${name}`);
|
|
684
|
+
}
|
|
685
|
+
const childInput = options.input !== void 0 ? options.input : this.input;
|
|
686
|
+
const childCtx = new _WorkflowContext({
|
|
687
|
+
notifier: this.notifier,
|
|
688
|
+
senderId: this.senderId,
|
|
689
|
+
workflow: this.workflow,
|
|
690
|
+
input: childInput,
|
|
691
|
+
state: this.state,
|
|
692
|
+
observability: this._observability,
|
|
693
|
+
executionId: this._executionId,
|
|
694
|
+
agentName: name
|
|
695
|
+
});
|
|
696
|
+
return agent.run(childCtx);
|
|
697
|
+
}
|
|
698
|
+
/** @param {object} opts */
|
|
699
|
+
async sendAI(opts) {
|
|
700
|
+
return this._invokeSdkApi(
|
|
701
|
+
"sendAI",
|
|
702
|
+
() => this.notifier.sendAI({
|
|
703
|
+
senderId: this.senderId,
|
|
704
|
+
...opts
|
|
705
|
+
}),
|
|
706
|
+
{
|
|
707
|
+
label: opts?.label,
|
|
708
|
+
input: opts?.message ?? apiInput(opts),
|
|
709
|
+
usesTokens: true
|
|
710
|
+
}
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
/** @param {object} [opts] */
|
|
714
|
+
async fetchAIHistory(opts = {}) {
|
|
715
|
+
return this._invokeSdkApi(
|
|
716
|
+
"fetchAIHistory",
|
|
717
|
+
() => this.notifier.fetchAIHistory({
|
|
718
|
+
senderId: this.senderId,
|
|
719
|
+
...opts
|
|
720
|
+
}),
|
|
721
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* @param {{ query: string, limit?: number, minSimilarity?: number, filterbySource?: string, label?: string }} opts
|
|
726
|
+
*/
|
|
727
|
+
async search(opts) {
|
|
728
|
+
return this._invokeSdkApi(
|
|
729
|
+
"search",
|
|
730
|
+
() => this.notifier.search({
|
|
731
|
+
senderId: this.senderId,
|
|
732
|
+
query: opts.query,
|
|
733
|
+
limit: opts.limit,
|
|
734
|
+
minSimilarity: opts.minSimilarity,
|
|
735
|
+
filterbySource: opts.filterbySource
|
|
736
|
+
}),
|
|
737
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
738
|
+
);
|
|
739
|
+
}
|
|
740
|
+
/** @param {object} opts */
|
|
741
|
+
async addDocument(opts) {
|
|
742
|
+
return this._invokeSdkApi(
|
|
743
|
+
"addDocument",
|
|
744
|
+
() => this.notifier.addDocument({
|
|
745
|
+
senderId: this.senderId,
|
|
746
|
+
...opts
|
|
747
|
+
}),
|
|
748
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
/** @param {object} opts */
|
|
752
|
+
async updateDocument(opts) {
|
|
753
|
+
return this._invokeSdkApi(
|
|
754
|
+
"updateDocument",
|
|
755
|
+
() => this.notifier.updateDocument({
|
|
756
|
+
senderId: this.senderId,
|
|
757
|
+
...opts
|
|
758
|
+
}),
|
|
759
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
/** @param {object} opts */
|
|
763
|
+
async deleteDocument(opts) {
|
|
764
|
+
return this._invokeSdkApi(
|
|
765
|
+
"deleteDocument",
|
|
766
|
+
() => this.notifier.deleteDocument({
|
|
767
|
+
senderId: this.senderId,
|
|
768
|
+
...opts
|
|
769
|
+
}),
|
|
770
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
/** @param {object} [opts] */
|
|
774
|
+
async listDocuments(opts = {}) {
|
|
775
|
+
return this._invokeSdkApi(
|
|
776
|
+
"listDocuments",
|
|
777
|
+
() => this.notifier.listDocuments({
|
|
778
|
+
senderId: this.senderId,
|
|
779
|
+
...opts
|
|
780
|
+
}),
|
|
781
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
/** @param {object} opts */
|
|
785
|
+
async getDocument(opts) {
|
|
786
|
+
return this._invokeSdkApi(
|
|
787
|
+
"getDocument",
|
|
788
|
+
() => this.notifier.getDocument({
|
|
789
|
+
senderId: this.senderId,
|
|
790
|
+
...opts
|
|
791
|
+
}),
|
|
792
|
+
{ label: opts?.label, input: apiInput(opts) }
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* @param {{
|
|
797
|
+
* kind?: string,
|
|
798
|
+
* label: string,
|
|
799
|
+
* input?: *,
|
|
800
|
+
* output?: *,
|
|
801
|
+
* status?: string,
|
|
802
|
+
* error?: object | null,
|
|
803
|
+
* type?: string,
|
|
804
|
+
* latencyMs?: number,
|
|
805
|
+
* }} step
|
|
806
|
+
*/
|
|
807
|
+
async recordStep(step) {
|
|
808
|
+
if (!this._observabilityEnabled) return;
|
|
809
|
+
const logType = step.type != null ? toLogStepType(step.type) : STEP_TYPE_CUSTOM;
|
|
810
|
+
await this._observability.recordStep(this._executionId, {
|
|
811
|
+
...step,
|
|
812
|
+
apiName: step.apiName ?? step.kind,
|
|
813
|
+
agentName: step.agentName ?? this.agentName,
|
|
814
|
+
kind: step.agentName ?? this.agentName ?? step.kind ?? "custom",
|
|
815
|
+
type: logType,
|
|
816
|
+
label: step.label ?? logType,
|
|
817
|
+
tokensIn: step.tokensIn ?? 0,
|
|
818
|
+
tokensOut: step.tokensOut ?? 0,
|
|
819
|
+
model: step.model ?? null,
|
|
820
|
+
latencyMs: step.latencyMs ?? 0,
|
|
821
|
+
status: step.status ?? "ok",
|
|
822
|
+
error: step.error ?? null,
|
|
823
|
+
input: snapshot(step.input),
|
|
824
|
+
output: snapshot(step.output)
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
|
|
829
|
+
// src/workflow/ids.js
|
|
285
830
|
function randomUUID() {
|
|
831
|
+
const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
832
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
833
|
+
if (c && c.getRandomValues) {
|
|
834
|
+
const bytes = new Uint8Array(16);
|
|
835
|
+
c.getRandomValues(bytes);
|
|
836
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
837
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
838
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
839
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
840
|
+
}
|
|
841
|
+
return `id_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
842
|
+
}
|
|
843
|
+
function shortId(prefix) {
|
|
844
|
+
return `${prefix}_${randomUUID().replace(/-/g, "").slice(0, 12)}`;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// src/workflow/jsonPayload.js
|
|
848
|
+
function toJsonColumn(value) {
|
|
849
|
+
if (value === void 0 || value === null) {
|
|
850
|
+
return null;
|
|
851
|
+
}
|
|
852
|
+
if (typeof value === "string") {
|
|
853
|
+
const trimmed = value.trim();
|
|
854
|
+
if (trimmed === "") {
|
|
855
|
+
return {};
|
|
856
|
+
}
|
|
857
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
858
|
+
try {
|
|
859
|
+
return JSON.parse(trimmed);
|
|
860
|
+
} catch {
|
|
861
|
+
return { text: value };
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return { text: value };
|
|
865
|
+
}
|
|
866
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
867
|
+
return value;
|
|
868
|
+
}
|
|
869
|
+
try {
|
|
870
|
+
return JSON.parse(
|
|
871
|
+
JSON.stringify(
|
|
872
|
+
value,
|
|
873
|
+
(_key, v) => typeof v === "bigint" ? v.toString() : v
|
|
874
|
+
)
|
|
875
|
+
);
|
|
876
|
+
} catch {
|
|
877
|
+
return { text: String(value) };
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
function setJsonColumn(target, key, value) {
|
|
881
|
+
const normalized = toJsonColumn(value);
|
|
882
|
+
if (normalized !== null) {
|
|
883
|
+
target[key] = normalized;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
// src/workflow/workflowObservabilityClient.js
|
|
888
|
+
var WorkflowObservabilityClient = class {
|
|
889
|
+
/**
|
|
890
|
+
* @param {{ appId?: string, token?: string | null }} [options]
|
|
891
|
+
*/
|
|
892
|
+
constructor({ appId = null, token = null } = {}) {
|
|
893
|
+
this.appId = appId;
|
|
894
|
+
this.token = token;
|
|
895
|
+
}
|
|
896
|
+
configure({ appId, token } = {}) {
|
|
897
|
+
if (appId !== void 0) this.appId = appId;
|
|
898
|
+
if (token !== void 0) this.token = token;
|
|
899
|
+
}
|
|
900
|
+
_transport(url) {
|
|
901
|
+
const headers = this.token ? { authorization: `${this.token}` } : {};
|
|
902
|
+
return new HttpTransport({ url, headers });
|
|
903
|
+
}
|
|
904
|
+
async _post(url, body) {
|
|
905
|
+
if (!this.token) {
|
|
906
|
+
console.warn("[WorkflowObservability] skip API call: not connected (no auth token)");
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
try {
|
|
910
|
+
await this._transport(url).send(body);
|
|
911
|
+
} catch (err) {
|
|
912
|
+
console.log(
|
|
913
|
+
`[WorkflowObservability] API failed (${url}):`,
|
|
914
|
+
err?.message ?? err
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* @param {object} payload
|
|
920
|
+
*/
|
|
921
|
+
async registerWorkflow(payload) {
|
|
922
|
+
const body = {
|
|
923
|
+
appId: payload.appId,
|
|
924
|
+
workflowId: payload.workflowId,
|
|
925
|
+
name: payload.name
|
|
926
|
+
};
|
|
927
|
+
if (payload.description != null && payload.description !== "") {
|
|
928
|
+
body.description = payload.description;
|
|
929
|
+
}
|
|
930
|
+
await this._post(DNotifierEndpoints.workflowRegisterUrl, body);
|
|
931
|
+
return { ok: true };
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* @param {object} payload
|
|
935
|
+
*/
|
|
936
|
+
async createExecution(payload) {
|
|
937
|
+
const executionId = payload.id ?? shortId("exec");
|
|
938
|
+
const body = {
|
|
939
|
+
id: executionId,
|
|
940
|
+
appId: payload.appId,
|
|
941
|
+
workflowId: payload.workflowId,
|
|
942
|
+
userId: payload.userId,
|
|
943
|
+
status: "in_progress",
|
|
944
|
+
stepCount: 0,
|
|
945
|
+
startedAt: payload.startedAt
|
|
946
|
+
};
|
|
947
|
+
setJsonColumn(body, "input", payload.input);
|
|
948
|
+
await this._post(DNotifierEndpoints.workflowExecutionsUrl, body);
|
|
949
|
+
return { executionId, record: body };
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* @param {string} executionId
|
|
953
|
+
* @param {object} patch
|
|
954
|
+
*/
|
|
955
|
+
async updateExecution(executionId, patch) {
|
|
956
|
+
const body = {
|
|
957
|
+
id: executionId,
|
|
958
|
+
status: patch.status,
|
|
959
|
+
endedAt: patch.endedAt,
|
|
960
|
+
durationMs: patch.durationMs,
|
|
961
|
+
stepCount: patch.stepCount
|
|
962
|
+
};
|
|
963
|
+
setJsonColumn(body, "error", patch.error);
|
|
964
|
+
setJsonColumn(body, "result", patch.result);
|
|
965
|
+
await this._post(
|
|
966
|
+
DNotifierEndpoints.workflowExecutionCompleteUrl(executionId),
|
|
967
|
+
body
|
|
968
|
+
);
|
|
969
|
+
return { ok: true, record: body };
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* @param {string} executionId
|
|
973
|
+
* @param {object} step
|
|
974
|
+
*/
|
|
975
|
+
async addStep(executionId, step) {
|
|
976
|
+
const stepType = resolveStepType(step);
|
|
977
|
+
const kind = step.agentName ?? step.kind ?? step.apiName ?? null;
|
|
978
|
+
const body = {
|
|
979
|
+
id: step.id,
|
|
980
|
+
executionId,
|
|
981
|
+
kind,
|
|
982
|
+
label: step.label,
|
|
983
|
+
type: stepType,
|
|
984
|
+
step_type: stepType,
|
|
985
|
+
status: step.status,
|
|
986
|
+
executedAt: step.executedAt,
|
|
987
|
+
latencyMs: step.latencyMs ?? 0,
|
|
988
|
+
tokensIn: step.tokensIn ?? 0,
|
|
989
|
+
tokensOut: step.tokensOut ?? 0
|
|
990
|
+
};
|
|
991
|
+
if (step.apiName != null && step.apiName !== "") {
|
|
992
|
+
body.apiName = step.apiName;
|
|
993
|
+
}
|
|
994
|
+
if (step.agentName != null && step.agentName !== "") {
|
|
995
|
+
body.agentName = step.agentName;
|
|
996
|
+
}
|
|
997
|
+
console.log("[WorkflowObservability] step kind:", {
|
|
998
|
+
kind: body.kind,
|
|
999
|
+
type: body.type,
|
|
1000
|
+
agentName: body.agentName,
|
|
1001
|
+
apiName: body.apiName,
|
|
1002
|
+
stepKind: step.kind,
|
|
1003
|
+
stepAgentName: step.agentName,
|
|
1004
|
+
stepApiName: step.apiName
|
|
1005
|
+
});
|
|
1006
|
+
if (step.model != null && step.model !== "") {
|
|
1007
|
+
body.model = typeof step.model === "string" ? step.model : String(step.model);
|
|
1008
|
+
}
|
|
1009
|
+
setJsonColumn(body, "input", step.input);
|
|
1010
|
+
setJsonColumn(body, "output", step.output);
|
|
1011
|
+
setJsonColumn(body, "error", step.error);
|
|
1012
|
+
await this._post(
|
|
1013
|
+
DNotifierEndpoints.workflowExecutionStepsUrl(executionId),
|
|
1014
|
+
body
|
|
1015
|
+
);
|
|
1016
|
+
return { ok: true };
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
1019
|
+
|
|
1020
|
+
// src/workflow/observability.js
|
|
1021
|
+
var WorkflowObservability = class {
|
|
1022
|
+
/**
|
|
1023
|
+
* @param {{ appId: string, token?: string | null, client?: WorkflowObservabilityClient }} options
|
|
1024
|
+
*/
|
|
1025
|
+
constructor({ appId, token = null, client }) {
|
|
1026
|
+
this.appId = appId;
|
|
1027
|
+
this.token = token;
|
|
1028
|
+
this.client = client ?? new WorkflowObservabilityClient({ appId, token });
|
|
1029
|
+
this.client.configure({ appId, token });
|
|
1030
|
+
this._registeredWorkflowNames = /* @__PURE__ */ new Set();
|
|
1031
|
+
this._stepCounter = 0;
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* @param {import("./workflow.js").Workflow} workflow
|
|
1035
|
+
*/
|
|
1036
|
+
async registerWorkflow(workflow) {
|
|
1037
|
+
if (this._registeredWorkflowNames.has(workflow.name)) return;
|
|
1038
|
+
this._registeredWorkflowNames.add(workflow.name);
|
|
1039
|
+
try {
|
|
1040
|
+
await this.client.registerWorkflow({
|
|
1041
|
+
appId: this.appId,
|
|
1042
|
+
workflowId: workflow.name,
|
|
1043
|
+
name: workflow.name,
|
|
1044
|
+
description: workflow.description ?? null
|
|
1045
|
+
});
|
|
1046
|
+
} catch (err) {
|
|
1047
|
+
console.warn("[WorkflowObservability] registerWorkflow failed:", err?.message ?? err);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* @param {object} params
|
|
1052
|
+
*/
|
|
1053
|
+
async startExecution(params) {
|
|
1054
|
+
const executionId = shortId("exec");
|
|
1055
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1056
|
+
try {
|
|
1057
|
+
await this.client.createExecution({
|
|
1058
|
+
id: executionId,
|
|
1059
|
+
appId: this.appId,
|
|
1060
|
+
workflowId: params.workflowId,
|
|
1061
|
+
userId: params.userId,
|
|
1062
|
+
input: params.input ?? null,
|
|
1063
|
+
startedAt
|
|
1064
|
+
});
|
|
1065
|
+
} catch (err) {
|
|
1066
|
+
console.warn("[WorkflowObservability] startExecution failed:", err?.message ?? err);
|
|
1067
|
+
}
|
|
1068
|
+
this._stepCounter = 0;
|
|
1069
|
+
return { executionId, startedAt };
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* @param {string} executionId
|
|
1073
|
+
* @param {object} step
|
|
1074
|
+
*/
|
|
1075
|
+
async recordStep(executionId, step) {
|
|
1076
|
+
if (!executionId) return;
|
|
1077
|
+
this._stepCounter += 1;
|
|
1078
|
+
const id = step.id ?? `n${this._stepCounter}`;
|
|
1079
|
+
const type = resolveStepType(step);
|
|
1080
|
+
const kind = step.agentName ?? step.kind ?? step.apiName ?? null;
|
|
1081
|
+
const record = {
|
|
1082
|
+
...step,
|
|
1083
|
+
id,
|
|
1084
|
+
executionId,
|
|
1085
|
+
executedAt: step.executedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1086
|
+
apiName: step.apiName ?? null,
|
|
1087
|
+
agentName: step.agentName ?? null,
|
|
1088
|
+
kind,
|
|
1089
|
+
type,
|
|
1090
|
+
step_type: type
|
|
1091
|
+
};
|
|
1092
|
+
try {
|
|
1093
|
+
await this.client.addStep(executionId, record);
|
|
1094
|
+
} catch (err) {
|
|
1095
|
+
console.warn("[WorkflowObservability] recordStep failed:", err?.message ?? err);
|
|
1096
|
+
}
|
|
1097
|
+
return record;
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* @param {object} params
|
|
1101
|
+
*/
|
|
1102
|
+
async completeExecution(params) {
|
|
1103
|
+
if (!params.executionId) return;
|
|
1104
|
+
try {
|
|
1105
|
+
await this.client.updateExecution(params.executionId, {
|
|
1106
|
+
status: params.status,
|
|
1107
|
+
endedAt: params.endedAt,
|
|
1108
|
+
durationMs: params.durationMs,
|
|
1109
|
+
stepCount: params.stepCount,
|
|
1110
|
+
error: params.error ?? null,
|
|
1111
|
+
result: params.result ?? null
|
|
1112
|
+
});
|
|
1113
|
+
} catch (err) {
|
|
1114
|
+
console.warn("[WorkflowObservability] completeExecution failed:", err?.message ?? err);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
getStepCount() {
|
|
1118
|
+
return this._stepCounter;
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
function createWorkflowObservability(params) {
|
|
1122
|
+
return new WorkflowObservability(params);
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// src/workflow/runner.js
|
|
1126
|
+
var WorkflowRunner = class {
|
|
1127
|
+
/**
|
|
1128
|
+
* @param {{
|
|
1129
|
+
* notifier: import("../dnotifier.js").DNotifier,
|
|
1130
|
+
* senderId: string,
|
|
1131
|
+
* workflow: import("./workflow.js").Workflow,
|
|
1132
|
+
* }} options
|
|
1133
|
+
*/
|
|
1134
|
+
constructor({ notifier, senderId, workflow }) {
|
|
1135
|
+
if (!notifier) throw new WorkflowError("WorkflowRunner requires a DNotifier instance");
|
|
1136
|
+
if (!senderId) throw new WorkflowError("WorkflowRunner requires senderId");
|
|
1137
|
+
if (!workflow) throw new WorkflowError("WorkflowRunner requires a workflow");
|
|
1138
|
+
this.notifier = notifier;
|
|
1139
|
+
this.senderId = senderId;
|
|
1140
|
+
this.workflow = workflow;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* @param {{ input: * }} params
|
|
1144
|
+
*/
|
|
1145
|
+
async run(params) {
|
|
1146
|
+
const input = params?.input;
|
|
1147
|
+
const state = {};
|
|
1148
|
+
let observability = null;
|
|
1149
|
+
let executionId = null;
|
|
1150
|
+
let startedAt = null;
|
|
1151
|
+
const runStarted = Date.now();
|
|
1152
|
+
if (this.workflow.observability) {
|
|
1153
|
+
observability = createWorkflowObservability({
|
|
1154
|
+
appId: this.notifier.appId,
|
|
1155
|
+
token: this.notifier.authToken ?? null
|
|
1156
|
+
});
|
|
1157
|
+
await observability.registerWorkflow(this.workflow);
|
|
1158
|
+
const started = await observability.startExecution({
|
|
1159
|
+
workflowId: this.workflow.name,
|
|
1160
|
+
userId: this.senderId,
|
|
1161
|
+
input
|
|
1162
|
+
});
|
|
1163
|
+
executionId = started.executionId;
|
|
1164
|
+
startedAt = started.startedAt;
|
|
1165
|
+
}
|
|
1166
|
+
const ctx = new WorkflowContext({
|
|
1167
|
+
notifier: this.notifier,
|
|
1168
|
+
senderId: this.senderId,
|
|
1169
|
+
workflow: this.workflow,
|
|
1170
|
+
input,
|
|
1171
|
+
state,
|
|
1172
|
+
observability,
|
|
1173
|
+
executionId
|
|
1174
|
+
});
|
|
1175
|
+
let result;
|
|
1176
|
+
let status = "ok";
|
|
1177
|
+
let errorPayload = null;
|
|
1178
|
+
try {
|
|
1179
|
+
result = await this.workflow.entry(ctx);
|
|
1180
|
+
} catch (err) {
|
|
1181
|
+
status = "error";
|
|
1182
|
+
errorPayload = {
|
|
1183
|
+
message: err?.message ?? String(err),
|
|
1184
|
+
stack: err?.stack
|
|
1185
|
+
};
|
|
1186
|
+
throw err;
|
|
1187
|
+
} finally {
|
|
1188
|
+
if (observability && executionId) {
|
|
1189
|
+
const endedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1190
|
+
const stepCount = observability.getStepCount();
|
|
1191
|
+
await observability.completeExecution({
|
|
1192
|
+
executionId,
|
|
1193
|
+
status,
|
|
1194
|
+
endedAt,
|
|
1195
|
+
durationMs: Date.now() - runStarted,
|
|
1196
|
+
stepCount,
|
|
1197
|
+
error: errorPayload,
|
|
1198
|
+
result: status === "ok" ? result : null,
|
|
1199
|
+
startedAt
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
const out = { result, state };
|
|
1204
|
+
if (executionId) out.executionId = executionId;
|
|
1205
|
+
return out;
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
|
|
1209
|
+
// src/dnotifier.js
|
|
1210
|
+
function randomUUID2() {
|
|
286
1211
|
const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
287
1212
|
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
288
1213
|
if (c && c.getRandomValues) {
|
|
@@ -295,15 +1220,28 @@ function randomUUID() {
|
|
|
295
1220
|
}
|
|
296
1221
|
throw new Error("DNotifier: no secure random (crypto.getRandomValues or crypto.randomUUID) available");
|
|
297
1222
|
}
|
|
298
|
-
var _defaultWsUrl =
|
|
299
|
-
var _defaultAuthUrl =
|
|
300
|
-
var _defaultHttpUrl =
|
|
1223
|
+
var _defaultWsUrl = DNotifierEndpoints.wsUrl;
|
|
1224
|
+
var _defaultAuthUrl = DNotifierEndpoints.authUrl;
|
|
1225
|
+
var _defaultHttpUrl = DNotifierEndpoints.rpcSendUrl;
|
|
301
1226
|
var DNotifier = class {
|
|
1227
|
+
/** @type {typeof Agent} */
|
|
1228
|
+
static Agent = Agent;
|
|
1229
|
+
/** @type {typeof defineAgent} */
|
|
1230
|
+
static defineAgent = defineAgent;
|
|
1231
|
+
/** @type {typeof Workflow} */
|
|
1232
|
+
static Workflow = Workflow;
|
|
1233
|
+
/** @type {typeof WorkflowContext} */
|
|
1234
|
+
static WorkflowContext = WorkflowContext;
|
|
1235
|
+
/** @type {typeof WorkflowRunner} */
|
|
1236
|
+
static WorkflowRunner = WorkflowRunner;
|
|
1237
|
+
/** @type {typeof WorkflowError} */
|
|
1238
|
+
static WorkflowError = WorkflowError;
|
|
302
1239
|
constructor({
|
|
303
1240
|
appId,
|
|
304
1241
|
secret,
|
|
305
1242
|
transport,
|
|
306
1243
|
userId,
|
|
1244
|
+
logs = false,
|
|
307
1245
|
url,
|
|
308
1246
|
onConnected,
|
|
309
1247
|
onMessage,
|
|
@@ -327,6 +1265,11 @@ var DNotifier = class {
|
|
|
327
1265
|
this.isConnected = false;
|
|
328
1266
|
this.aiEnabled = false;
|
|
329
1267
|
this.messageSizeLimit = 32 * 1024;
|
|
1268
|
+
this._logsEnabled = Boolean(logs);
|
|
1269
|
+
this._logsClient = new LogsClient({
|
|
1270
|
+
enabled: this._logsEnabled,
|
|
1271
|
+
appId: this.appId
|
|
1272
|
+
});
|
|
330
1273
|
this.transport = transport === "ws" ? new WebsocketTransport(WebSocketImpl) : new HttpTransport({ url: _defaultHttpUrl });
|
|
331
1274
|
}
|
|
332
1275
|
async connect() {
|
|
@@ -348,6 +1291,16 @@ var DNotifier = class {
|
|
|
348
1291
|
this.authToken = res._responseData.token;
|
|
349
1292
|
this.aiEnabled = res._responseData.limits?.aiEnabled ?? false;
|
|
350
1293
|
this.messageSizeLimit = (res._responseData.limits?.messageSizeKB ?? 32) * 1024;
|
|
1294
|
+
this.currentModel = res._responseData.current_model;
|
|
1295
|
+
this._logsClient.configure({
|
|
1296
|
+
token: this.authToken,
|
|
1297
|
+
model: this.currentModel
|
|
1298
|
+
});
|
|
1299
|
+
if (this.transport instanceof HttpTransport) {
|
|
1300
|
+
this.isConnected = true;
|
|
1301
|
+
this.onConnectedCallback();
|
|
1302
|
+
return true;
|
|
1303
|
+
}
|
|
351
1304
|
if (this.transport instanceof WebsocketTransport) {
|
|
352
1305
|
await this.transport.connect(this.url);
|
|
353
1306
|
const metadata = {
|
|
@@ -380,6 +1333,15 @@ var DNotifier = class {
|
|
|
380
1333
|
}
|
|
381
1334
|
return combined;
|
|
382
1335
|
};
|
|
1336
|
+
const normalizePayloadBuffer = (value) => {
|
|
1337
|
+
if (value == null) return toUint8("");
|
|
1338
|
+
if (value instanceof Uint8Array || value instanceof ArrayBuffer) return value;
|
|
1339
|
+
if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(value)) {
|
|
1340
|
+
return value;
|
|
1341
|
+
}
|
|
1342
|
+
if (typeof value === "string") return toUint8(value);
|
|
1343
|
+
return toUint8(JSON.stringify(value));
|
|
1344
|
+
};
|
|
383
1345
|
this.transport.on("message", (chunk) => {
|
|
384
1346
|
try {
|
|
385
1347
|
const { metadata: metadata2, data } = chunk;
|
|
@@ -396,10 +1358,25 @@ var DNotifier = class {
|
|
|
396
1358
|
const totalPackets = packet.totalPackets ?? 1;
|
|
397
1359
|
const currentPacket = packet.currentPacket ?? 1;
|
|
398
1360
|
const messageId = packet.id;
|
|
1361
|
+
let promptResponse = null;
|
|
399
1362
|
if (totalPackets === 1 || !messageId) {
|
|
1363
|
+
if (packet.code == "300") {
|
|
1364
|
+
try {
|
|
1365
|
+
promptResponse = new Payload(data).toJSON();
|
|
1366
|
+
this._logsClient.completeAiLogging({
|
|
1367
|
+
sessionId: messageId,
|
|
1368
|
+
response: promptResponse
|
|
1369
|
+
}).catch((err) => {
|
|
1370
|
+
console.error("Session step completion failed:", err);
|
|
1371
|
+
});
|
|
1372
|
+
} catch (err) {
|
|
1373
|
+
console.error("Session step completion failed:", err);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
400
1376
|
this.onMessageCallback({
|
|
401
1377
|
metadata: {
|
|
402
|
-
|
|
1378
|
+
id: packet.id,
|
|
1379
|
+
type: packet.type ?? packet.sender,
|
|
403
1380
|
sender: packet.sender,
|
|
404
1381
|
timestamp: packet.timestamp
|
|
405
1382
|
},
|
|
@@ -417,9 +1394,19 @@ var DNotifier = class {
|
|
|
417
1394
|
if (entry.chunks.some((c) => c === null)) return;
|
|
418
1395
|
const fullBuffer = mergeChunks(entry.chunks);
|
|
419
1396
|
messageBuffers.delete(messageId);
|
|
1397
|
+
if (packet.code === 300) {
|
|
1398
|
+
promptResponse = new Payload(fullBuffer).toJSON();
|
|
1399
|
+
this._logsClient.completeAiLogging({
|
|
1400
|
+
sessionId: messageId,
|
|
1401
|
+
response: promptResponse
|
|
1402
|
+
}).catch((err) => {
|
|
1403
|
+
console.error("Session step completion failed:", err);
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
420
1406
|
this.onMessageCallback({
|
|
421
1407
|
metadata: {
|
|
422
|
-
|
|
1408
|
+
id: packet.id,
|
|
1409
|
+
type: packet.type ?? packet.sender,
|
|
423
1410
|
sender: packet.sender,
|
|
424
1411
|
timestamp: packet.timestamp
|
|
425
1412
|
},
|
|
@@ -446,9 +1433,6 @@ var DNotifier = class {
|
|
|
446
1433
|
reason: err?.message || "Transport error"
|
|
447
1434
|
});
|
|
448
1435
|
});
|
|
449
|
-
} else {
|
|
450
|
-
this.isConnected = true;
|
|
451
|
-
this.onConnectedCallback();
|
|
452
1436
|
}
|
|
453
1437
|
}
|
|
454
1438
|
/**
|
|
@@ -479,7 +1463,7 @@ var DNotifier = class {
|
|
|
479
1463
|
const receivers = receiverIds ?? [receiverId2];
|
|
480
1464
|
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
481
1465
|
const chunkSizeBytes = this.messageSizeLimit || 32 * 1024;
|
|
482
|
-
const messageId =
|
|
1466
|
+
const messageId = randomUUID2();
|
|
483
1467
|
const metadata = {
|
|
484
1468
|
id: messageId,
|
|
485
1469
|
type: "text",
|
|
@@ -493,6 +1477,9 @@ var DNotifier = class {
|
|
|
493
1477
|
token: this.authToken,
|
|
494
1478
|
saveHistory
|
|
495
1479
|
};
|
|
1480
|
+
if (this.transport instanceof HttpTransport) {
|
|
1481
|
+
return await this.transport.send({ metadata, data });
|
|
1482
|
+
}
|
|
496
1483
|
if (this.transport instanceof WebsocketTransport) {
|
|
497
1484
|
if (payloadBuffer.length <= chunkSizeBytes) {
|
|
498
1485
|
this.transport.sendBinary(framePacket(metadata, payloadBuffer));
|
|
@@ -520,8 +1507,6 @@ var DNotifier = class {
|
|
|
520
1507
|
this.transport.sendBinary(framePacket(metadata2, chunk));
|
|
521
1508
|
});
|
|
522
1509
|
return messageId;
|
|
523
|
-
} else {
|
|
524
|
-
return await this.transport.send({ metadata, data });
|
|
525
1510
|
}
|
|
526
1511
|
}
|
|
527
1512
|
/**
|
|
@@ -531,35 +1516,51 @@ var DNotifier = class {
|
|
|
531
1516
|
* @param {string | object} options.message - Message or payload to send to AI.
|
|
532
1517
|
* @returns {string} - The message id.
|
|
533
1518
|
*/
|
|
534
|
-
async sendAI({ senderId, message, saveHistory = true }) {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
1519
|
+
async sendAI({ senderId, message, saveHistory = true, sessionId = null }) {
|
|
1520
|
+
try {
|
|
1521
|
+
if (!this.isConnected) throw new Error("Not connected");
|
|
1522
|
+
if (!senderId) throw new Error("senderId required");
|
|
1523
|
+
const _msgId = sessionId ?? randomUUID2();
|
|
1524
|
+
const metadata = {
|
|
1525
|
+
id: _msgId,
|
|
1526
|
+
type: "ai",
|
|
1527
|
+
code: 300,
|
|
1528
|
+
appId: this.appId,
|
|
1529
|
+
sender: prefixId(this.appId, senderId),
|
|
1530
|
+
receiverId: prefixId(this.appId, senderId),
|
|
1531
|
+
timestamp: Date.now(),
|
|
1532
|
+
token: this.authToken,
|
|
1533
|
+
saveHistory
|
|
1534
|
+
};
|
|
1535
|
+
await this._logsClient.startAiLogging({
|
|
1536
|
+
sessionId: _msgId,
|
|
1537
|
+
prompts: message,
|
|
1538
|
+
isExistingSession: Boolean(sessionId)
|
|
1539
|
+
});
|
|
1540
|
+
if (this.transport instanceof HttpTransport) {
|
|
1541
|
+
const response = await this.transport.send({ metadata, data: message });
|
|
1542
|
+
await this._logsClient.completeAiLogging({
|
|
1543
|
+
sessionId: _msgId,
|
|
1544
|
+
response
|
|
1545
|
+
});
|
|
1546
|
+
return response;
|
|
1547
|
+
}
|
|
1548
|
+
if (this.transport instanceof WebsocketTransport) {
|
|
1549
|
+
const payloadBuffer = toUint8(JSON.stringify(message));
|
|
1550
|
+
const frame = framePacket(metadata, payloadBuffer);
|
|
1551
|
+
this.transport.sendBinary(frame);
|
|
1552
|
+
}
|
|
1553
|
+
return _msgId;
|
|
1554
|
+
} catch (err) {
|
|
1555
|
+
console.error("error in sendAI:", err);
|
|
1556
|
+
return null;
|
|
555
1557
|
}
|
|
556
|
-
return _msgId;
|
|
557
1558
|
}
|
|
558
1559
|
async fetchAIHistory({ senderId }) {
|
|
559
1560
|
if (!this.isConnected) throw new Error("Not connected");
|
|
560
1561
|
if (!senderId) throw new Error("senderId required");
|
|
561
1562
|
const metadata = {
|
|
562
|
-
id:
|
|
1563
|
+
id: randomUUID2(),
|
|
563
1564
|
type: "ai",
|
|
564
1565
|
code: 301,
|
|
565
1566
|
appId: this.appId,
|
|
@@ -567,12 +1568,13 @@ var DNotifier = class {
|
|
|
567
1568
|
timestamp: Date.now(),
|
|
568
1569
|
token: this.authToken
|
|
569
1570
|
};
|
|
1571
|
+
if (this.transport instanceof HttpTransport) {
|
|
1572
|
+
return await this.transport.send({ metadata, data: {} });
|
|
1573
|
+
}
|
|
570
1574
|
if (this.transport instanceof WebsocketTransport) {
|
|
571
1575
|
const payloadBuffer = toUint8(JSON.stringify({}));
|
|
572
1576
|
const frame = framePacket(metadata, payloadBuffer);
|
|
573
1577
|
this.transport.sendBinary(frame);
|
|
574
|
-
} else {
|
|
575
|
-
return await this.transport.send({ metadata, data: {} });
|
|
576
1578
|
}
|
|
577
1579
|
}
|
|
578
1580
|
/**
|
|
@@ -586,7 +1588,7 @@ var DNotifier = class {
|
|
|
586
1588
|
throw new Error("receiverIds required");
|
|
587
1589
|
const receivers = receiverIds ?? [receiverId];
|
|
588
1590
|
const metadata = {
|
|
589
|
-
id:
|
|
1591
|
+
id: randomUUID2(),
|
|
590
1592
|
type: "text",
|
|
591
1593
|
code: 201,
|
|
592
1594
|
appId: this.appId,
|
|
@@ -595,12 +1597,13 @@ var DNotifier = class {
|
|
|
595
1597
|
timestamp: Date.now(),
|
|
596
1598
|
token: this.authToken
|
|
597
1599
|
};
|
|
1600
|
+
if (this.transport instanceof HttpTransport) {
|
|
1601
|
+
return await this.transport.send({ metadata, data: {} });
|
|
1602
|
+
}
|
|
598
1603
|
if (this.transport instanceof WebsocketTransport) {
|
|
599
1604
|
const payloadBuffer = toUint8(JSON.stringify({}));
|
|
600
1605
|
const frame = framePacket(metadata, payloadBuffer);
|
|
601
1606
|
this.transport.sendBinary(frame);
|
|
602
|
-
} else {
|
|
603
|
-
return await this.transport.send({ metadata, data: {} });
|
|
604
1607
|
}
|
|
605
1608
|
}
|
|
606
1609
|
/**
|
|
@@ -612,7 +1615,7 @@ var DNotifier = class {
|
|
|
612
1615
|
if (!senderId) throw new Error("senderId required");
|
|
613
1616
|
if (!messageId) throw new Error("messageId required");
|
|
614
1617
|
const metadata = {
|
|
615
|
-
id:
|
|
1618
|
+
id: randomUUID2(),
|
|
616
1619
|
type: "ai",
|
|
617
1620
|
code: 302,
|
|
618
1621
|
appId: this.appId,
|
|
@@ -621,12 +1624,13 @@ var DNotifier = class {
|
|
|
621
1624
|
token: this.authToken,
|
|
622
1625
|
messageId
|
|
623
1626
|
};
|
|
1627
|
+
if (this.transport instanceof HttpTransport) {
|
|
1628
|
+
return await this.transport.send({ metadata, data: { messageId } });
|
|
1629
|
+
}
|
|
624
1630
|
if (this.transport instanceof WebsocketTransport) {
|
|
625
1631
|
const payloadBuffer = toUint8(JSON.stringify({ messageId }));
|
|
626
1632
|
const frame = framePacket(metadata, payloadBuffer);
|
|
627
1633
|
this.transport.sendBinary(frame);
|
|
628
|
-
} else {
|
|
629
|
-
return await this.transport.send({ metadata, data: { messageId } });
|
|
630
1634
|
}
|
|
631
1635
|
}
|
|
632
1636
|
/**
|
|
@@ -638,7 +1642,7 @@ var DNotifier = class {
|
|
|
638
1642
|
if (!senderId) throw new Error("senderId required");
|
|
639
1643
|
if (!messageId) throw new Error("messageId required");
|
|
640
1644
|
const metadata = {
|
|
641
|
-
id:
|
|
1645
|
+
id: randomUUID2(),
|
|
642
1646
|
type: "text",
|
|
643
1647
|
code: 202,
|
|
644
1648
|
appId: this.appId,
|
|
@@ -648,12 +1652,13 @@ var DNotifier = class {
|
|
|
648
1652
|
token: this.authToken,
|
|
649
1653
|
messageId
|
|
650
1654
|
};
|
|
1655
|
+
if (this.transport instanceof HttpTransport) {
|
|
1656
|
+
return await this.transport.send({ metadata, data: { messageId } });
|
|
1657
|
+
}
|
|
651
1658
|
if (this.transport instanceof WebsocketTransport) {
|
|
652
1659
|
const payloadBuffer = toUint8(JSON.stringify({ messageId }));
|
|
653
1660
|
const frame = framePacket(metadata, payloadBuffer);
|
|
654
1661
|
this.transport.sendBinary(frame);
|
|
655
|
-
} else {
|
|
656
|
-
return await this.transport.send({ metadata, data: { messageId } });
|
|
657
1662
|
}
|
|
658
1663
|
}
|
|
659
1664
|
/**
|
|
@@ -665,7 +1670,7 @@ var DNotifier = class {
|
|
|
665
1670
|
if (!senderId) throw new Error("senderId required");
|
|
666
1671
|
if (!query) throw new Error("query required");
|
|
667
1672
|
const metadata = {
|
|
668
|
-
id:
|
|
1673
|
+
id: randomUUID2(),
|
|
669
1674
|
type: "ai",
|
|
670
1675
|
code: 303,
|
|
671
1676
|
appId: this.appId,
|
|
@@ -673,6 +1678,11 @@ var DNotifier = class {
|
|
|
673
1678
|
timestamp: Date.now(),
|
|
674
1679
|
token: this.authToken
|
|
675
1680
|
};
|
|
1681
|
+
if (this.transport instanceof HttpTransport) {
|
|
1682
|
+
const data = { query, limit, minSimilarity };
|
|
1683
|
+
if (filterbySource !== void 0) data.filterbySource = filterbySource;
|
|
1684
|
+
return await this.transport.send({ metadata, data });
|
|
1685
|
+
}
|
|
676
1686
|
if (this.transport instanceof WebsocketTransport) {
|
|
677
1687
|
const payloadBuffer = toUint8(
|
|
678
1688
|
JSON.stringify({
|
|
@@ -684,10 +1694,6 @@ var DNotifier = class {
|
|
|
684
1694
|
);
|
|
685
1695
|
const frame = framePacket(metadata, payloadBuffer);
|
|
686
1696
|
this.transport.sendBinary(frame);
|
|
687
|
-
} else {
|
|
688
|
-
const data = { query, limit, minSimilarity };
|
|
689
|
-
if (filterbySource !== void 0) data.filterbySource = filterbySource;
|
|
690
|
-
return await this.transport.send({ metadata, data });
|
|
691
1697
|
}
|
|
692
1698
|
}
|
|
693
1699
|
/**
|
|
@@ -714,7 +1720,7 @@ var DNotifier = class {
|
|
|
714
1720
|
if (type != null) data.type = String(type);
|
|
715
1721
|
if (docMetadata && typeof docMetadata === "object") data.metadata = docMetadata;
|
|
716
1722
|
const metadata = {
|
|
717
|
-
id:
|
|
1723
|
+
id: randomUUID2(),
|
|
718
1724
|
type: "ai",
|
|
719
1725
|
code: 306,
|
|
720
1726
|
appId: this.appId,
|
|
@@ -722,12 +1728,13 @@ var DNotifier = class {
|
|
|
722
1728
|
timestamp: Date.now(),
|
|
723
1729
|
token: this.authToken
|
|
724
1730
|
};
|
|
1731
|
+
if (this.transport instanceof HttpTransport) {
|
|
1732
|
+
return await this.transport.send({ metadata, data });
|
|
1733
|
+
}
|
|
725
1734
|
if (this.transport instanceof WebsocketTransport) {
|
|
726
1735
|
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
727
1736
|
const frame = framePacket(metadata, payloadBuffer);
|
|
728
1737
|
this.transport.sendBinary(frame);
|
|
729
|
-
} else {
|
|
730
|
-
return await this.transport.send({ metadata, data });
|
|
731
1738
|
}
|
|
732
1739
|
}
|
|
733
1740
|
/**
|
|
@@ -754,7 +1761,7 @@ var DNotifier = class {
|
|
|
754
1761
|
if (type != null) data.type = String(type);
|
|
755
1762
|
if (docMetadata && typeof docMetadata === "object") data.metadata = docMetadata;
|
|
756
1763
|
const metadata = {
|
|
757
|
-
id:
|
|
1764
|
+
id: randomUUID2(),
|
|
758
1765
|
type: "ai",
|
|
759
1766
|
code: 307,
|
|
760
1767
|
appId: this.appId,
|
|
@@ -762,11 +1769,12 @@ var DNotifier = class {
|
|
|
762
1769
|
timestamp: Date.now(),
|
|
763
1770
|
token: this.authToken
|
|
764
1771
|
};
|
|
1772
|
+
if (this.transport instanceof HttpTransport) {
|
|
1773
|
+
return await this.transport.send({ metadata, data });
|
|
1774
|
+
}
|
|
765
1775
|
if (this.transport instanceof WebsocketTransport) {
|
|
766
1776
|
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
767
1777
|
this.transport.sendBinary(framePacket(metadata, payloadBuffer));
|
|
768
|
-
} else {
|
|
769
|
-
return await this.transport.send({ metadata, data });
|
|
770
1778
|
}
|
|
771
1779
|
}
|
|
772
1780
|
/**
|
|
@@ -781,7 +1789,7 @@ var DNotifier = class {
|
|
|
781
1789
|
if (!rid) throw new Error("recordId is required");
|
|
782
1790
|
const data = { recordId: rid };
|
|
783
1791
|
const metadata = {
|
|
784
|
-
id:
|
|
1792
|
+
id: randomUUID2(),
|
|
785
1793
|
type: "ai",
|
|
786
1794
|
code: 308,
|
|
787
1795
|
appId: this.appId,
|
|
@@ -789,11 +1797,12 @@ var DNotifier = class {
|
|
|
789
1797
|
timestamp: Date.now(),
|
|
790
1798
|
token: this.authToken
|
|
791
1799
|
};
|
|
1800
|
+
if (this.transport instanceof HttpTransport) {
|
|
1801
|
+
return await this.transport.send({ metadata, data });
|
|
1802
|
+
}
|
|
792
1803
|
if (this.transport instanceof WebsocketTransport) {
|
|
793
1804
|
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
794
1805
|
this.transport.sendBinary(framePacket(metadata, payloadBuffer));
|
|
795
|
-
} else {
|
|
796
|
-
return await this.transport.send({ metadata, data });
|
|
797
1806
|
}
|
|
798
1807
|
}
|
|
799
1808
|
/**
|
|
@@ -808,7 +1817,7 @@ var DNotifier = class {
|
|
|
808
1817
|
if (offset != null) data.offset = offset;
|
|
809
1818
|
if (type != null) data.type = String(type);
|
|
810
1819
|
const metadata = {
|
|
811
|
-
id:
|
|
1820
|
+
id: randomUUID2(),
|
|
812
1821
|
type: "ai",
|
|
813
1822
|
code: 309,
|
|
814
1823
|
appId: this.appId,
|
|
@@ -816,11 +1825,12 @@ var DNotifier = class {
|
|
|
816
1825
|
timestamp: Date.now(),
|
|
817
1826
|
token: this.authToken
|
|
818
1827
|
};
|
|
1828
|
+
if (this.transport instanceof HttpTransport) {
|
|
1829
|
+
return await this.transport.send({ metadata, data });
|
|
1830
|
+
}
|
|
819
1831
|
if (this.transport instanceof WebsocketTransport) {
|
|
820
1832
|
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
821
1833
|
this.transport.sendBinary(framePacket(metadata, payloadBuffer));
|
|
822
|
-
} else {
|
|
823
|
-
return await this.transport.send({ metadata, data });
|
|
824
1834
|
}
|
|
825
1835
|
}
|
|
826
1836
|
/**
|
|
@@ -835,7 +1845,7 @@ var DNotifier = class {
|
|
|
835
1845
|
if (!rid) throw new Error("recordId is required");
|
|
836
1846
|
const data = { recordId: rid };
|
|
837
1847
|
const metadata = {
|
|
838
|
-
id:
|
|
1848
|
+
id: randomUUID2(),
|
|
839
1849
|
type: "ai",
|
|
840
1850
|
code: 310,
|
|
841
1851
|
appId: this.appId,
|
|
@@ -843,11 +1853,12 @@ var DNotifier = class {
|
|
|
843
1853
|
timestamp: Date.now(),
|
|
844
1854
|
token: this.authToken
|
|
845
1855
|
};
|
|
1856
|
+
if (this.transport instanceof HttpTransport) {
|
|
1857
|
+
return await this.transport.send({ metadata, data });
|
|
1858
|
+
}
|
|
846
1859
|
if (this.transport instanceof WebsocketTransport) {
|
|
847
1860
|
const payloadBuffer = toUint8(JSON.stringify(data));
|
|
848
1861
|
this.transport.sendBinary(framePacket(metadata, payloadBuffer));
|
|
849
|
-
} else {
|
|
850
|
-
return await this.transport.send({ metadata, data });
|
|
851
1862
|
}
|
|
852
1863
|
}
|
|
853
1864
|
sendBinary({ senderId, receiverIds, buffer, type = "binary" }) {
|
|
@@ -884,8 +1895,32 @@ var DNotifier = class {
|
|
|
884
1895
|
if (!message) throw new Error("message is required");
|
|
885
1896
|
this.sendAI({ senderId, message });
|
|
886
1897
|
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Run a registered workflow after connect().
|
|
1900
|
+
* @param {{
|
|
1901
|
+
* workflow: import("./workflow/workflow.js").Workflow,
|
|
1902
|
+
* input: *,
|
|
1903
|
+
* senderId?: string,
|
|
1904
|
+
* }} options
|
|
1905
|
+
*/
|
|
1906
|
+
async runWorkflow({ workflow, input, senderId }) {
|
|
1907
|
+
if (!this.isConnected) throw new Error("Not connected");
|
|
1908
|
+
if (!workflow) throw new Error("workflow is required");
|
|
1909
|
+
const runner = new WorkflowRunner({
|
|
1910
|
+
notifier: this,
|
|
1911
|
+
senderId: senderId ?? this.userId,
|
|
1912
|
+
workflow
|
|
1913
|
+
});
|
|
1914
|
+
return runner.run({ input });
|
|
1915
|
+
}
|
|
887
1916
|
};
|
|
888
1917
|
// Annotate the CommonJS export names for ESM import in node:
|
|
889
1918
|
0 && (module.exports = {
|
|
890
|
-
|
|
1919
|
+
Agent,
|
|
1920
|
+
DNotifier,
|
|
1921
|
+
Workflow,
|
|
1922
|
+
WorkflowContext,
|
|
1923
|
+
WorkflowError,
|
|
1924
|
+
WorkflowRunner,
|
|
1925
|
+
defineAgent
|
|
891
1926
|
});
|