@dnotifier-realtime/dnotifier 1.1.8 → 1.1.12

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 (61) hide show
  1. package/README.md +531 -16
  2. package/dist/cjs/dnotifier.js +1 -1
  3. package/dist/cjs/providers/openai.js +1 -1
  4. package/dist/cjs/transport/httpTransport.js +1 -1
  5. package/dist/cjs/transport/websocketTransport.js +1 -1
  6. package/dist/cjs/utils/buffer.js +1 -1
  7. package/dist/cjs/utils/frame.js +1 -1
  8. package/dist/cjs/utils/id.js +1 -1
  9. package/dist/cjs/utils/payload.js +1 -1
  10. package/dist/config/endpoints.d.ts +9 -3
  11. package/dist/config/endpoints.d.ts.map +1 -1
  12. package/dist/config/endpoints.js +1 -1
  13. package/dist/dnotifier.cjs +872 -19
  14. package/dist/dnotifier.d.ts +22 -1
  15. package/dist/dnotifier.d.ts.map +1 -1
  16. package/dist/dnotifier.js +1 -1
  17. package/dist/providers/openai.js +1 -1
  18. package/dist/transport/httpTransport.js +1 -1
  19. package/dist/transport/websocketTransport.js +1 -1
  20. package/dist/utils/buffer.js +1 -1
  21. package/dist/utils/frame.js +1 -1
  22. package/dist/utils/id.js +1 -1
  23. package/dist/utils/logs.js +1 -1
  24. package/dist/utils/payload.js +1 -1
  25. package/dist/workflow/agent.d.ts +13 -0
  26. package/dist/workflow/agent.d.ts.map +1 -0
  27. package/dist/workflow/agent.js +1 -0
  28. package/dist/workflow/context.d.ts +54 -0
  29. package/dist/workflow/context.d.ts.map +1 -0
  30. package/dist/workflow/context.js +1 -0
  31. package/dist/workflow/errors.d.ts +9 -0
  32. package/dist/workflow/errors.d.ts.map +1 -0
  33. package/dist/workflow/errors.js +1 -0
  34. package/dist/workflow/ids.d.ts +3 -0
  35. package/dist/workflow/ids.d.ts.map +1 -0
  36. package/dist/workflow/ids.js +1 -0
  37. package/dist/workflow/index.d.ts +6 -0
  38. package/dist/workflow/index.d.ts.map +1 -0
  39. package/dist/workflow/index.js +1 -0
  40. package/dist/workflow/jsonPayload.d.ts +3 -0
  41. package/dist/workflow/jsonPayload.d.ts.map +1 -0
  42. package/dist/workflow/jsonPayload.js +1 -0
  43. package/dist/workflow/mockObservabilityClient.d.ts +47 -0
  44. package/dist/workflow/mockObservabilityClient.d.ts.map +1 -0
  45. package/dist/workflow/mockObservabilityClient.js +1 -0
  46. package/dist/workflow/observability.d.ts +35 -0
  47. package/dist/workflow/observability.d.ts.map +1 -0
  48. package/dist/workflow/observability.js +1 -0
  49. package/dist/workflow/runner.d.ts +17 -0
  50. package/dist/workflow/runner.d.ts.map +1 -0
  51. package/dist/workflow/runner.js +1 -0
  52. package/dist/workflow/stepTypes.d.ts +25 -0
  53. package/dist/workflow/stepTypes.d.ts.map +1 -0
  54. package/dist/workflow/stepTypes.js +1 -0
  55. package/dist/workflow/workflow.d.ts +18 -0
  56. package/dist/workflow/workflow.d.ts.map +1 -0
  57. package/dist/workflow/workflow.js +1 -0
  58. package/dist/workflow/workflowObservabilityClient.d.ts +41 -0
  59. package/dist/workflow/workflowObservabilityClient.d.ts.map +1 -0
  60. package/dist/workflow/workflowObservabilityClient.js +1 -0
  61. package/package.json +1 -1
@@ -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
- DNotifier: () => DNotifier
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
 
@@ -217,21 +223,31 @@ var WebsocketTransport = class extends import_events.default {
217
223
  };
218
224
 
219
225
  // src/config/endpoints.js
220
- var baseHost = "https://api.dnotifier.com";
226
+ var baseHost = "https://dev.api.dnotifier.com";
221
227
  var wsHost = baseHost.replace(/^http/, "ws");
222
228
  var logHost = `${baseHost}/ecs`;
229
+ var workflowSdkBase = `${logHost}/api/v1/log/sdk/workflow`;
223
230
  var DNotifierEndpoints = {
224
231
  // Change this host to switch all SDK endpoints.
225
232
  baseHost,
226
233
  // Core realtime/auth endpoints.
227
234
  wsUrl: `${wsHost}/ecs/ws`,
228
- authUrl: `${baseHost}/ecs/api/v1/sdk/auth`,
229
235
  rpcSendUrl: `${baseHost}/rpc/v1/message/send`,
236
+ authUrl: `${baseHost}/ecs/api/v1/sdk/auth`,
230
237
  // SDK log endpoints.
231
238
  logHost,
232
239
  addLogUrl: `${logHost}/api/v1/log/sdk/add-log`,
233
240
  updateLogStatusUrl: `${logHost}/api/v1/log/sdk/update-log-status`,
234
- addSessionStepUrl: `${logHost}/api/v1/log/sdk/add-session-step`
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`,
235
251
  };
236
252
 
237
253
  // src/utils/id.js
@@ -389,8 +405,809 @@ var LogsClient = class {
389
405
  }
390
406
  };
391
407
 
392
- // src/dnotifier.js
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
393
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() {
394
1211
  const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
395
1212
  if (c && typeof c.randomUUID === "function") return c.randomUUID();
396
1213
  if (c && c.getRandomValues) {
@@ -407,6 +1224,18 @@ var _defaultWsUrl = DNotifierEndpoints.wsUrl;
407
1224
  var _defaultAuthUrl = DNotifierEndpoints.authUrl;
408
1225
  var _defaultHttpUrl = DNotifierEndpoints.rpcSendUrl;
409
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;
410
1239
  constructor({
411
1240
  appId,
412
1241
  secret,
@@ -470,7 +1299,7 @@ var DNotifier = class {
470
1299
  if (this.transport instanceof HttpTransport) {
471
1300
  this.isConnected = true;
472
1301
  this.onConnectedCallback();
473
- return;
1302
+ return true;
474
1303
  }
475
1304
  if (this.transport instanceof WebsocketTransport) {
476
1305
  await this.transport.connect(this.url);
@@ -634,7 +1463,7 @@ var DNotifier = class {
634
1463
  const receivers = receiverIds ?? [receiverId2];
635
1464
  const payloadBuffer = toUint8(JSON.stringify(data));
636
1465
  const chunkSizeBytes = this.messageSizeLimit || 32 * 1024;
637
- const messageId = randomUUID();
1466
+ const messageId = randomUUID2();
638
1467
  const metadata = {
639
1468
  id: messageId,
640
1469
  type: "text",
@@ -691,7 +1520,7 @@ var DNotifier = class {
691
1520
  try {
692
1521
  if (!this.isConnected) throw new Error("Not connected");
693
1522
  if (!senderId) throw new Error("senderId required");
694
- const _msgId = sessionId ?? randomUUID();
1523
+ const _msgId = sessionId ?? randomUUID2();
695
1524
  const metadata = {
696
1525
  id: _msgId,
697
1526
  type: "ai",
@@ -731,7 +1560,7 @@ var DNotifier = class {
731
1560
  if (!this.isConnected) throw new Error("Not connected");
732
1561
  if (!senderId) throw new Error("senderId required");
733
1562
  const metadata = {
734
- id: randomUUID(),
1563
+ id: randomUUID2(),
735
1564
  type: "ai",
736
1565
  code: 301,
737
1566
  appId: this.appId,
@@ -759,7 +1588,7 @@ var DNotifier = class {
759
1588
  throw new Error("receiverIds required");
760
1589
  const receivers = receiverIds ?? [receiverId];
761
1590
  const metadata = {
762
- id: randomUUID(),
1591
+ id: randomUUID2(),
763
1592
  type: "text",
764
1593
  code: 201,
765
1594
  appId: this.appId,
@@ -786,7 +1615,7 @@ var DNotifier = class {
786
1615
  if (!senderId) throw new Error("senderId required");
787
1616
  if (!messageId) throw new Error("messageId required");
788
1617
  const metadata = {
789
- id: randomUUID(),
1618
+ id: randomUUID2(),
790
1619
  type: "ai",
791
1620
  code: 302,
792
1621
  appId: this.appId,
@@ -813,7 +1642,7 @@ var DNotifier = class {
813
1642
  if (!senderId) throw new Error("senderId required");
814
1643
  if (!messageId) throw new Error("messageId required");
815
1644
  const metadata = {
816
- id: randomUUID(),
1645
+ id: randomUUID2(),
817
1646
  type: "text",
818
1647
  code: 202,
819
1648
  appId: this.appId,
@@ -841,7 +1670,7 @@ var DNotifier = class {
841
1670
  if (!senderId) throw new Error("senderId required");
842
1671
  if (!query) throw new Error("query required");
843
1672
  const metadata = {
844
- id: randomUUID(),
1673
+ id: randomUUID2(),
845
1674
  type: "ai",
846
1675
  code: 303,
847
1676
  appId: this.appId,
@@ -891,7 +1720,7 @@ var DNotifier = class {
891
1720
  if (type != null) data.type = String(type);
892
1721
  if (docMetadata && typeof docMetadata === "object") data.metadata = docMetadata;
893
1722
  const metadata = {
894
- id: randomUUID(),
1723
+ id: randomUUID2(),
895
1724
  type: "ai",
896
1725
  code: 306,
897
1726
  appId: this.appId,
@@ -932,7 +1761,7 @@ var DNotifier = class {
932
1761
  if (type != null) data.type = String(type);
933
1762
  if (docMetadata && typeof docMetadata === "object") data.metadata = docMetadata;
934
1763
  const metadata = {
935
- id: randomUUID(),
1764
+ id: randomUUID2(),
936
1765
  type: "ai",
937
1766
  code: 307,
938
1767
  appId: this.appId,
@@ -960,7 +1789,7 @@ var DNotifier = class {
960
1789
  if (!rid) throw new Error("recordId is required");
961
1790
  const data = { recordId: rid };
962
1791
  const metadata = {
963
- id: randomUUID(),
1792
+ id: randomUUID2(),
964
1793
  type: "ai",
965
1794
  code: 308,
966
1795
  appId: this.appId,
@@ -988,7 +1817,7 @@ var DNotifier = class {
988
1817
  if (offset != null) data.offset = offset;
989
1818
  if (type != null) data.type = String(type);
990
1819
  const metadata = {
991
- id: randomUUID(),
1820
+ id: randomUUID2(),
992
1821
  type: "ai",
993
1822
  code: 309,
994
1823
  appId: this.appId,
@@ -1016,7 +1845,7 @@ var DNotifier = class {
1016
1845
  if (!rid) throw new Error("recordId is required");
1017
1846
  const data = { recordId: rid };
1018
1847
  const metadata = {
1019
- id: randomUUID(),
1848
+ id: randomUUID2(),
1020
1849
  type: "ai",
1021
1850
  code: 310,
1022
1851
  appId: this.appId,
@@ -1066,8 +1895,32 @@ var DNotifier = class {
1066
1895
  if (!message) throw new Error("message is required");
1067
1896
  this.sendAI({ senderId, message });
1068
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
+ }
1069
1916
  };
1070
1917
  // Annotate the CommonJS export names for ESM import in node:
1071
1918
  0 && (module.exports = {
1072
- DNotifier
1919
+ Agent,
1920
+ DNotifier,
1921
+ Workflow,
1922
+ WorkflowContext,
1923
+ WorkflowError,
1924
+ WorkflowRunner,
1925
+ defineAgent
1073
1926
  });