@dnotifier-realtime/dnotifier 1.1.18 → 1.1.23

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 (52) hide show
  1. package/dist/cjs/dnotifier.js +1 -1
  2. package/dist/cjs/providers/openai.js +1 -1
  3. package/dist/cjs/transport/httpTransport.js +1 -1
  4. package/dist/cjs/transport/websocketTransport.js +1 -1
  5. package/dist/cjs/utils/buffer.js +1 -1
  6. package/dist/cjs/utils/frame.js +1 -1
  7. package/dist/cjs/utils/id.js +1 -1
  8. package/dist/cjs/utils/payload.js +1 -1
  9. package/dist/config/endpoints.d.ts.map +1 -1
  10. package/dist/config/endpoints.js +1 -1
  11. package/dist/dnotifier.cjs +584 -96
  12. package/dist/dnotifier.d.ts +34 -2
  13. package/dist/dnotifier.d.ts.map +1 -1
  14. package/dist/dnotifier.js +1 -1
  15. package/dist/providers/openai.js +1 -1
  16. package/dist/transport/httpTransport.js +1 -1
  17. package/dist/transport/websocketTransport.js +1 -1
  18. package/dist/utils/buffer.js +1 -1
  19. package/dist/utils/frame.js +1 -1
  20. package/dist/utils/id.js +1 -1
  21. package/dist/utils/logs.d.ts +2 -1
  22. package/dist/utils/logs.d.ts.map +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 +7 -1
  26. package/dist/workflow/agent.d.ts.map +1 -1
  27. package/dist/workflow/agent.js +1 -1
  28. package/dist/workflow/context.d.ts +15 -1
  29. package/dist/workflow/context.d.ts.map +1 -1
  30. package/dist/workflow/context.js +1 -1
  31. package/dist/workflow/errors.js +1 -1
  32. package/dist/workflow/graphParents.js +1 -1
  33. package/dist/workflow/ids.js +1 -1
  34. package/dist/workflow/index.d.ts +1 -0
  35. package/dist/workflow/index.js +1 -1
  36. package/dist/workflow/jsonPayload.js +1 -1
  37. package/dist/workflow/mockObservabilityClient.js +1 -1
  38. package/dist/workflow/observability.js +1 -1
  39. package/dist/workflow/remoteAgentClient.d.ts +30 -0
  40. package/dist/workflow/remoteAgentClient.d.ts.map +1 -0
  41. package/dist/workflow/remoteAgentClient.js +1 -0
  42. package/dist/workflow/remoteAgentProtocol.d.ts +50 -0
  43. package/dist/workflow/remoteAgentProtocol.d.ts.map +1 -0
  44. package/dist/workflow/remoteAgentProtocol.js +1 -0
  45. package/dist/workflow/runner.js +1 -1
  46. package/dist/workflow/stepTypes.js +1 -1
  47. package/dist/workflow/workflow.d.ts +15 -3
  48. package/dist/workflow/workflow.d.ts.map +1 -1
  49. package/dist/workflow/workflow.js +1 -1
  50. package/dist/workflow/workflowObservabilityClient.d.ts.map +1 -1
  51. package/dist/workflow/workflowObservabilityClient.js +1 -1
  52. package/package.json +2 -1
@@ -262,8 +262,6 @@ var DNotifierEndpoints = {
262
262
  workflowExecutionUrl: (executionId) => `${workflowSdkBase}/executions/${executionId}`,
263
263
  workflowExecutionCompleteUrl: (executionId) => `${workflowSdkBase}/executions/${executionId}/complete`,
264
264
  workflowExecutionStepsUrl: (executionId) => `${workflowSdkBase}/executions/${executionId}/steps`
265
- // wsUrl:`ws://localhost:7072`,
266
- // rpcSendUrl:`http://localhost:8081/rpc/v1/message/send`,
267
265
  };
268
266
 
269
267
  // src/utils/id.js
@@ -365,10 +363,11 @@ var LogsClient = class {
365
363
  async addSessionStepLog(payload) {
366
364
  return await this._transport(DEFAULT_SESSION_STEP_URL).send(payload);
367
365
  }
368
- async startAiLogging({ sessionId, prompts, isExistingSession = false }) {
366
+ async startAiLogging({ sessionId, prompts, isExistingSession = false, model = null }) {
369
367
  if (!this.enabled) return;
370
368
  if (!this.token || !this.appId || !sessionId) return;
371
369
  const createdDate = (/* @__PURE__ */ new Date()).toISOString();
370
+ const logModel = model != null && String(model).trim() !== "" ? model : this.model;
372
371
  if (isExistingSession) {
373
372
  await this.updateLog({
374
373
  sessionId,
@@ -380,7 +379,7 @@ var LogsClient = class {
380
379
  appId: this.appId,
381
380
  sessionId,
382
381
  status: "InProgress",
383
- model: this.model,
382
+ model: logModel,
384
383
  calls: 1,
385
384
  createdDate,
386
385
  step: 1
@@ -392,7 +391,8 @@ var LogsClient = class {
392
391
  tokens: 0,
393
392
  status: "InProgress",
394
393
  prompts,
395
- createdDate
394
+ createdDate,
395
+ model: logModel
396
396
  });
397
397
  }
398
398
  async completeAiLogging({ sessionId, response = null }) {
@@ -440,9 +440,14 @@ var WorkflowError = class extends Error {
440
440
  // src/workflow/agent.js
441
441
  var Agent = class {
442
442
  /**
443
- * @param {{ name: string, run: (ctx: import("./context.js").WorkflowContext) => Promise<*> }} config
443
+ * @param {{
444
+ * name: string,
445
+ * run: (ctx: import("./context.js").WorkflowContext) => Promise<*>,
446
+ * provider?: string | null,
447
+ * model?: string | null,
448
+ * }} config
444
449
  */
445
- constructor({ name, run }) {
450
+ constructor({ name, run, provider = null, model = null }) {
446
451
  if (!name || typeof name !== "string") {
447
452
  throw new WorkflowError("Agent name is required");
448
453
  }
@@ -451,80 +456,146 @@ var Agent = class {
451
456
  }
452
457
  this.name = name;
453
458
  this.run = run;
459
+ this.provider = provider != null && provider !== "" ? provider : null;
460
+ this.model = model != null && model !== "" ? model : null;
454
461
  }
455
462
  };
456
463
  function defineAgent(config) {
457
464
  return new Agent(config);
458
465
  }
459
466
 
460
- // src/workflow/workflow.js
461
- function normalizeDescription(description) {
462
- if (description === void 0 || description === null || description === "") {
463
- return void 0;
464
- }
465
- if (typeof description !== "string") {
466
- throw new WorkflowError("Workflow description must be a string");
467
- }
468
- const trimmed = description.trim();
469
- if (trimmed.length > 100) {
470
- throw new WorkflowError("Workflow description must be at most 100 characters");
471
- }
472
- return trimmed.length > 0 ? trimmed : void 0;
467
+ // src/workflow/remoteAgentProtocol.js
468
+ var REMOTE_AGENT_KIND = "dnotifier.remoteAgent";
469
+ var REMOTE_AGENT_OP = {
470
+ INVOKE: "invoke",
471
+ RESULT: "result",
472
+ ERROR: "error"
473
+ };
474
+ function isRemoteAgentEnvelope(data) {
475
+ return data != null && typeof data === "object" && data.__dnotifier === REMOTE_AGENT_KIND && typeof data.op === "string";
473
476
  }
474
- var Workflow = class {
475
- /**
476
- * @param {{
477
- * name: string,
478
- * description?: string,
479
- * observability?: boolean,
480
- * entry: (ctx: import("./context.js").WorkflowContext) => Promise<*>,
481
- * }} options
482
- */
483
- constructor({ name, description, observability = false, entry }) {
484
- if (!name || typeof name !== "string") {
485
- throw new WorkflowError("Workflow name is required");
486
- }
487
- if (typeof entry !== "function") {
488
- throw new WorkflowError("Workflow entry must be a function");
489
- }
490
- this.name = name.trim();
491
- this.description = normalizeDescription(description);
492
- this.observability = Boolean(observability);
493
- this.entry = entry;
494
- this._agents = /* @__PURE__ */ new Map();
495
- this._registeredWithObservability = false;
496
- }
497
- /**
498
- * @param {string} name
499
- * @param {import("./agent.js").Agent} agent
500
- */
501
- registerAgent(name, agent) {
502
- if (!name || typeof name !== "string") {
503
- throw new WorkflowError("Agent registration name is required");
504
- }
505
- if (!agent || typeof agent.run !== "function") {
506
- throw new WorkflowError(`Invalid agent for "${name}"`);
507
- }
508
- this._agents.set(name, agent);
509
- return this;
510
- }
511
- /**
512
- * @param {Record<string, import("./agent.js").Agent>} agents
513
- */
514
- registerAgents(agents) {
515
- for (const [name, agent] of Object.entries(agents)) {
516
- this.registerAgent(name, agent);
517
- }
518
- return this;
519
- }
520
- /**
521
- * @param {string} name
522
- * @returns {import("./agent.js").Agent | undefined}
523
- */
524
- getAgent(name) {
525
- return this._agents.get(name);
477
+ function isRemoteAgentRef(value) {
478
+ return value != null && typeof value === "object" && typeof value.receiverId === "string" && value.receiverId.trim() !== "" && typeof value.run !== "function";
479
+ }
480
+ function createInvokeEnvelope(params) {
481
+ return {
482
+ __dnotifier: REMOTE_AGENT_KIND,
483
+ op: REMOTE_AGENT_OP.INVOKE,
484
+ correlationId: params.correlationId,
485
+ agentName: params.agentName,
486
+ input: params.input ?? null,
487
+ state: params.state ?? null,
488
+ trace: params.trace ?? null,
489
+ replyTo: params.replyTo
490
+ };
491
+ }
492
+ function createResultEnvelope(params) {
493
+ return {
494
+ __dnotifier: REMOTE_AGENT_KIND,
495
+ op: REMOTE_AGENT_OP.RESULT,
496
+ correlationId: params.correlationId,
497
+ output: params.output ?? null,
498
+ state: params.state ?? null
499
+ };
500
+ }
501
+ function createErrorEnvelope(params) {
502
+ return {
503
+ __dnotifier: REMOTE_AGENT_KIND,
504
+ op: REMOTE_AGENT_OP.ERROR,
505
+ correlationId: params.correlationId,
506
+ error: { message: params.message }
507
+ };
508
+ }
509
+
510
+ // src/workflow/remoteAgentClient.js
511
+ var DEFAULT_TIMEOUT_MS = 12e4;
512
+ function correlationId() {
513
+ const c = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
514
+ if (c && typeof c.randomUUID === "function") return c.randomUUID();
515
+ if (c && c.getRandomValues) {
516
+ const bytes = new Uint8Array(16);
517
+ c.getRandomValues(bytes);
518
+ bytes[6] = bytes[6] & 15 | 64;
519
+ bytes[8] = bytes[8] & 63 | 128;
520
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
521
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
526
522
  }
527
- };
523
+ return `corr_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
524
+ }
525
+ function bareUserId(appId, prefixedSender) {
526
+ if (!prefixedSender || typeof prefixedSender !== "string") return "";
527
+ const prefix = `${appId}:`;
528
+ if (prefixedSender.startsWith(prefix)) {
529
+ return prefixedSender.slice(prefix.length);
530
+ }
531
+ const idx = prefixedSender.indexOf(":");
532
+ if (idx >= 0) return prefixedSender.slice(idx + 1);
533
+ return prefixedSender;
534
+ }
535
+ async function invokeRemoteAgent(params) {
536
+ const {
537
+ notifier,
538
+ senderId,
539
+ receiverId: receiverId2,
540
+ agentName,
541
+ input,
542
+ state,
543
+ trace = null,
544
+ timeoutMs = DEFAULT_TIMEOUT_MS
545
+ } = params;
546
+ if (!notifier?.isConnected) {
547
+ throw new WorkflowError("Remote agent invoke requires a connected notifier");
548
+ }
549
+ if (!receiverId2) {
550
+ throw new WorkflowError(`Remote agent "${agentName}" is missing receiverId`);
551
+ }
552
+ const id = correlationId();
553
+ const envelope = createInvokeEnvelope({
554
+ correlationId: id,
555
+ agentName,
556
+ input,
557
+ state: state ?? null,
558
+ trace,
559
+ replyTo: senderId
560
+ });
561
+ const resultPromise = notifier._awaitRemoteAgentReply(id, {
562
+ timeoutMs,
563
+ agentName
564
+ });
565
+ await notifier.send({
566
+ senderId,
567
+ receiverId: receiverId2,
568
+ data: envelope,
569
+ saveHistory: false
570
+ });
571
+ return resultPromise;
572
+ }
573
+ async function sendRemoteAgentResult(notifier, params) {
574
+ await notifier.send({
575
+ senderId: params.senderId,
576
+ receiverId: params.receiverId,
577
+ data: createResultEnvelope({
578
+ correlationId: params.correlationId,
579
+ output: params.output,
580
+ state: params.state ?? null
581
+ }),
582
+ saveHistory: false
583
+ });
584
+ }
585
+ async function sendRemoteAgentError(notifier, params) {
586
+ await notifier.send({
587
+ senderId: params.senderId,
588
+ receiverId: params.receiverId,
589
+ data: createErrorEnvelope({
590
+ correlationId: params.correlationId,
591
+ message: params.message
592
+ }),
593
+ saveHistory: false
594
+ });
595
+ }
596
+ function isRemoteAgentReply(data) {
597
+ return data != null && typeof data === "object" && (data.op === REMOTE_AGENT_OP.RESULT || data.op === REMOTE_AGENT_OP.ERROR);
598
+ }
528
599
 
529
600
  // src/workflow/graphParents.js
530
601
  function formatParentStepId(value) {
@@ -641,6 +712,12 @@ function usageFromResponse(response) {
641
712
  const model = response?.data?.model ?? usage.model ?? null;
642
713
  return { tokensIn, tokensOut, model };
643
714
  }
715
+ function firstNonEmpty(...values) {
716
+ for (const value of values) {
717
+ if (value != null && String(value).trim() !== "") return value;
718
+ }
719
+ return null;
720
+ }
644
721
  function snapshot(value) {
645
722
  try {
646
723
  if (value === void 0) return null;
@@ -693,6 +770,8 @@ var WorkflowContext = class _WorkflowContext {
693
770
  * agentName?: string | null,
694
771
  * entryStepId?: string | null,
695
772
  * traceParentStepId?: string | null,
773
+ * provider?: string | null,
774
+ * model?: string | null,
696
775
  * }} options
697
776
  */
698
777
  constructor({
@@ -705,7 +784,9 @@ var WorkflowContext = class _WorkflowContext {
705
784
  executionId = null,
706
785
  agentName = null,
707
786
  entryStepId = null,
708
- traceParentStepId = null
787
+ traceParentStepId = null,
788
+ provider = null,
789
+ model = null
709
790
  }) {
710
791
  this.notifier = notifier;
711
792
  this.senderId = senderId;
@@ -722,6 +803,8 @@ var WorkflowContext = class _WorkflowContext {
722
803
  this._currentStepId = null;
723
804
  this.rootStepId = null;
724
805
  this._terminalStepIds = [];
806
+ this._aiProvider = provider != null && provider !== "" ? provider : null;
807
+ this._aiModel = model != null && model !== "" ? model : null;
725
808
  }
726
809
  /**
727
810
  * Comma-separated parent step ids for the workflow End node.
@@ -767,7 +850,13 @@ var WorkflowContext = class _WorkflowContext {
767
850
  /**
768
851
  * @param {string} apiName
769
852
  * @param {() => Promise<*>} invoke
770
- * @param {{ label?: string, input?: *, usesTokens?: boolean }} [meta]
853
+ * @param {{
854
+ * label?: string,
855
+ * input?: *,
856
+ * usesTokens?: boolean,
857
+ * provider?: string | null,
858
+ * model?: string | null,
859
+ * }} [meta]
771
860
  */
772
861
  async _invokeSdkApi(apiName, invoke, meta = {}) {
773
862
  const started = Date.now();
@@ -785,6 +874,12 @@ var WorkflowContext = class _WorkflowContext {
785
874
  } finally {
786
875
  if (this._observabilityEnabled) {
787
876
  const usage = meta.usesTokens ? usageFromResponse(output) : { tokensIn: 0, tokensOut: 0, model: null };
877
+ const model = firstNonEmpty(
878
+ meta.model,
879
+ usage.model,
880
+ this.notifier?.currentModel
881
+ );
882
+ const provider = firstNonEmpty(meta.provider);
788
883
  const stepKind = this.agentName ?? apiName;
789
884
  await this._observability.recordStep(this._executionId, {
790
885
  apiName,
@@ -796,6 +891,8 @@ var WorkflowContext = class _WorkflowContext {
796
891
  latencyMs: Date.now() - started,
797
892
  parentStepId: formatParentStepId(this._currentStepId),
798
893
  ...usage,
894
+ model,
895
+ provider,
799
896
  input: snapshot(meta.input),
800
897
  output: snapshot(output),
801
898
  state: snapshot(this.state),
@@ -813,12 +910,13 @@ var WorkflowContext = class _WorkflowContext {
813
910
  * branchKey?: string,
814
911
  * siblingIndex?: number,
815
912
  * parentStepId?: string | null,
913
+ * timeoutMs?: number,
816
914
  * }} [options]
817
915
  * @returns {Promise<{ output: *, stepId: string | null }>}
818
916
  */
819
917
  async _runAgentObserved(name, options = {}) {
820
- const agent = this.workflow.getAgent(name);
821
- if (!agent) {
918
+ const registration = this.workflow.getAgentRegistration(name);
919
+ if (!registration) {
822
920
  throw new WorkflowError(`Agent not found: ${name}`);
823
921
  }
824
922
  const childInput = options.input !== void 0 ? options.input : this.input;
@@ -834,6 +932,29 @@ var WorkflowContext = class _WorkflowContext {
834
932
  let output = null;
835
933
  let error = null;
836
934
  try {
935
+ if (isRemoteAgentRef(registration)) {
936
+ const trace = this._executionId ? {
937
+ executionId: this._executionId,
938
+ workflowId: this.workflow.name,
939
+ parentStepId: agentStepId ?? this._currentStepId ?? this._chainHeadStepId ?? this._traceParentStepId ?? this._entryStepId ?? null
940
+ } : null;
941
+ const remote = await invokeRemoteAgent({
942
+ notifier: this.notifier,
943
+ senderId: this.senderId,
944
+ receiverId: registration.receiverId,
945
+ agentName: name,
946
+ input: childInput,
947
+ state: this.state,
948
+ trace,
949
+ timeoutMs: options.timeoutMs
950
+ });
951
+ if (remote.state && typeof remote.state === "object") {
952
+ Object.assign(this.state, remote.state);
953
+ }
954
+ output = remote.output;
955
+ return { output, stepId: agentStepId };
956
+ }
957
+ const agent = registration;
837
958
  const childCtx = new _WorkflowContext({
838
959
  notifier: this.notifier,
839
960
  senderId: this.senderId,
@@ -844,7 +965,9 @@ var WorkflowContext = class _WorkflowContext {
844
965
  executionId: this._executionId,
845
966
  agentName: name,
846
967
  entryStepId: this._entryStepId,
847
- traceParentStepId: this._traceParentStepId
968
+ traceParentStepId: this._traceParentStepId,
969
+ provider: agent.provider ?? null,
970
+ model: agent.model ?? null
848
971
  });
849
972
  childCtx._currentStepId = agentStepId;
850
973
  output = await agent.run(childCtx);
@@ -890,6 +1013,7 @@ var WorkflowContext = class _WorkflowContext {
890
1013
  * branchKey?: string,
891
1014
  * siblingIndex?: number,
892
1015
  * parentStepId?: string | null,
1016
+ * timeoutMs?: number,
893
1017
  * }} [options]
894
1018
  */
895
1019
  async runAgent(name, options = {}) {
@@ -899,6 +1023,20 @@ var WorkflowContext = class _WorkflowContext {
899
1023
  }
900
1024
  return output;
901
1025
  }
1026
+ /**
1027
+ * Wait for the next inbound realtime message (non-protocol).
1028
+ * Use WebSocket transport. Useful mid-agent for human/service follow-ups.
1029
+ * @param {{ timeoutMs?: number }} [options]
1030
+ * @returns {Promise<{ metadata: object, payload: * }>}
1031
+ */
1032
+ async waitForMessage(options = {}) {
1033
+ if (!this.notifier || typeof this.notifier._waitForInboundMessage !== "function") {
1034
+ throw new WorkflowError("waitForMessage requires a DNotifier instance");
1035
+ }
1036
+ return this.notifier._waitForInboundMessage({
1037
+ timeoutMs: options.timeoutMs
1038
+ });
1039
+ }
902
1040
  /**
903
1041
  * @param {Array<string | { name: string, input?: * }> | Record<string, *>} spec
904
1042
  * @param {{ label?: string }} [options]
@@ -933,16 +1071,22 @@ var WorkflowContext = class _WorkflowContext {
933
1071
  }
934
1072
  /** @param {object} opts */
935
1073
  async sendAI(opts) {
1074
+ const provider = opts?.provider ?? this._aiProvider ?? void 0;
1075
+ const model = opts?.model ?? this._aiModel ?? void 0;
936
1076
  return this._invokeSdkApi(
937
1077
  "sendAI",
938
1078
  () => this.notifier.sendAI({
939
1079
  senderId: this.senderId,
940
- ...opts
1080
+ ...opts,
1081
+ provider,
1082
+ model
941
1083
  }),
942
1084
  {
943
1085
  label: opts?.label,
944
1086
  input: opts?.message ?? apiInput(opts),
945
- usesTokens: true
1087
+ usesTokens: true,
1088
+ provider,
1089
+ model
946
1090
  }
947
1091
  );
948
1092
  }
@@ -1240,6 +1384,9 @@ var WorkflowObservabilityClient = class {
1240
1384
  if (step.model != null && step.model !== "") {
1241
1385
  body.model = typeof step.model === "string" ? step.model : String(step.model);
1242
1386
  }
1387
+ if (step.provider != null && step.provider !== "") {
1388
+ body.provider = typeof step.provider === "string" ? step.provider : String(step.provider);
1389
+ }
1243
1390
  setJsonColumn(body, "input", step.input);
1244
1391
  setJsonColumn(body, "output", step.output);
1245
1392
  setJsonColumn(body, "state", step.state);
@@ -1384,6 +1531,179 @@ function createWorkflowObservability(params) {
1384
1531
  return new WorkflowObservability(params);
1385
1532
  }
1386
1533
 
1534
+ // src/workflow/workflow.js
1535
+ function normalizeDescription(description) {
1536
+ if (description === void 0 || description === null || description === "") {
1537
+ return void 0;
1538
+ }
1539
+ if (typeof description !== "string") {
1540
+ throw new WorkflowError("Workflow description must be a string");
1541
+ }
1542
+ const trimmed = description.trim();
1543
+ if (trimmed.length > 100) {
1544
+ throw new WorkflowError("Workflow description must be at most 100 characters");
1545
+ }
1546
+ return trimmed.length > 0 ? trimmed : void 0;
1547
+ }
1548
+ var Workflow = class {
1549
+ /**
1550
+ * @param {{
1551
+ * name: string,
1552
+ * description?: string,
1553
+ * observability?: boolean,
1554
+ * entry: (ctx: import("./context.js").WorkflowContext) => Promise<*>,
1555
+ * }} options
1556
+ */
1557
+ constructor({ name, description, observability = false, entry }) {
1558
+ if (!name || typeof name !== "string") {
1559
+ throw new WorkflowError("Workflow name is required");
1560
+ }
1561
+ if (typeof entry !== "function") {
1562
+ throw new WorkflowError("Workflow entry must be a function");
1563
+ }
1564
+ this.name = name.trim();
1565
+ this.description = normalizeDescription(description);
1566
+ this.observability = Boolean(observability);
1567
+ this.entry = entry;
1568
+ this._agents = /* @__PURE__ */ new Map();
1569
+ this._registeredWithObservability = false;
1570
+ this._listenNotifier = null;
1571
+ }
1572
+ /**
1573
+ * @param {string} name
1574
+ * @param {AgentRegistration} agentOrRemote
1575
+ */
1576
+ registerAgent(name, agentOrRemote) {
1577
+ if (!name || typeof name !== "string") {
1578
+ throw new WorkflowError("Agent registration name is required");
1579
+ }
1580
+ if (isRemoteAgentRef(agentOrRemote)) {
1581
+ this._agents.set(name, { receiverId: agentOrRemote.receiverId.trim() });
1582
+ return this;
1583
+ }
1584
+ if (!agentOrRemote || typeof agentOrRemote.run !== "function") {
1585
+ throw new WorkflowError(
1586
+ `Invalid agent for "${name}" (expected Agent or { receiverId })`
1587
+ );
1588
+ }
1589
+ this._agents.set(name, agentOrRemote);
1590
+ return this;
1591
+ }
1592
+ /**
1593
+ * @param {Record<string, AgentRegistration>} agents
1594
+ */
1595
+ registerAgents(agents) {
1596
+ for (const [name, agent] of Object.entries(agents)) {
1597
+ this.registerAgent(name, agent);
1598
+ }
1599
+ return this;
1600
+ }
1601
+ /**
1602
+ * Local Agent only (undefined if missing or remote).
1603
+ * @param {string} name
1604
+ * @returns {import("./agent.js").Agent | undefined}
1605
+ */
1606
+ getAgent(name) {
1607
+ const reg = this._agents.get(name);
1608
+ if (!reg || isRemoteAgentRef(reg)) return void 0;
1609
+ return reg;
1610
+ }
1611
+ /**
1612
+ * @param {string} name
1613
+ * @returns {AgentRegistration | undefined}
1614
+ */
1615
+ getAgentRegistration(name) {
1616
+ return this._agents.get(name);
1617
+ }
1618
+ /**
1619
+ * @param {string} name
1620
+ * @returns {boolean}
1621
+ */
1622
+ hasLocalAgent(name) {
1623
+ return Boolean(this.getAgent(name));
1624
+ }
1625
+ /**
1626
+ * Answer remote `runAgent` invokes for local agents on this workflow.
1627
+ * Uses WorkflowContext → ctx.runAgent (agents are never called directly).
1628
+ * Requires WebSocket transport so replies can be sent/received.
1629
+ * @param {import("../dnotifier.js").DNotifier} notifier
1630
+ */
1631
+ listen(notifier) {
1632
+ if (!notifier) {
1633
+ throw new WorkflowError("workflow.listen requires a DNotifier instance");
1634
+ }
1635
+ if (this._listenNotifier && this._listenNotifier !== notifier) {
1636
+ this._listenNotifier._unregisterWorkflowListener(this);
1637
+ }
1638
+ this._listenNotifier = notifier;
1639
+ notifier._registerWorkflowListener(this);
1640
+ return this;
1641
+ }
1642
+ /**
1643
+ * @internal
1644
+ * @param {import("../dnotifier.js").DNotifier} notifier
1645
+ * @param {{ metadata: object, payload: * }} msg
1646
+ * @param {object} data
1647
+ */
1648
+ async _handleRemoteInvoke(notifier, msg, data) {
1649
+ const agentName = data.agentName;
1650
+ const correlationId2 = data.correlationId;
1651
+ const replyTo = typeof data.replyTo === "string" && data.replyTo.trim() || bareUserId(notifier.appId, msg?.metadata?.sender);
1652
+ if (!correlationId2 || !replyTo) {
1653
+ return;
1654
+ }
1655
+ if (!this.hasLocalAgent(agentName)) {
1656
+ await sendRemoteAgentError(notifier, {
1657
+ senderId: notifier.userId,
1658
+ receiverId: replyTo,
1659
+ correlationId: correlationId2,
1660
+ message: `Agent not hosted: ${agentName}`
1661
+ });
1662
+ return;
1663
+ }
1664
+ const inboundState = data.state && typeof data.state === "object" && !Array.isArray(data.state) ? { ...data.state } : {};
1665
+ let observability = null;
1666
+ const executionId = data.trace?.executionId ?? null;
1667
+ if (executionId && this.observability) {
1668
+ observability = createWorkflowObservability({
1669
+ appId: notifier.appId,
1670
+ token: notifier.authToken ?? null,
1671
+ appendOnly: true
1672
+ });
1673
+ await observability.registerWorkflow(this);
1674
+ }
1675
+ const ctx = new WorkflowContext({
1676
+ notifier,
1677
+ senderId: notifier.userId,
1678
+ workflow: this,
1679
+ input: data.input ?? null,
1680
+ state: inboundState,
1681
+ observability,
1682
+ executionId,
1683
+ traceParentStepId: data.trace?.parentStepId ?? null
1684
+ });
1685
+ try {
1686
+ const output = await ctx.runAgent(agentName, {
1687
+ input: data.input !== void 0 ? data.input : ctx.input
1688
+ });
1689
+ await sendRemoteAgentResult(notifier, {
1690
+ senderId: notifier.userId,
1691
+ receiverId: replyTo,
1692
+ correlationId: correlationId2,
1693
+ output,
1694
+ state: ctx.state
1695
+ });
1696
+ } catch (err) {
1697
+ await sendRemoteAgentError(notifier, {
1698
+ senderId: notifier.userId,
1699
+ receiverId: replyTo,
1700
+ correlationId: correlationId2,
1701
+ message: err?.message ?? String(err)
1702
+ });
1703
+ }
1704
+ }
1705
+ };
1706
+
1387
1707
  // src/workflow/runner.js
1388
1708
  function snapshot2(value) {
1389
1709
  try {
@@ -1519,6 +1839,15 @@ function randomUUID2() {
1519
1839
  var _defaultWsUrl = DNotifierEndpoints.wsUrl;
1520
1840
  var _defaultAuthUrl = DNotifierEndpoints.authUrl;
1521
1841
  var _defaultHttpUrl = DNotifierEndpoints.rpcSendUrl;
1842
+ function buildAiSendData(message, { provider, model } = {}) {
1843
+ const hasProvider = provider != null && String(provider).trim() !== "";
1844
+ const hasModel = model != null && String(model).trim() !== "";
1845
+ if (!hasProvider && !hasModel) return message;
1846
+ const data = message != null && typeof message === "object" && !Array.isArray(message) ? { ...message } : message != null ? { text: message } : {};
1847
+ if (hasProvider) data.provider = provider;
1848
+ if (hasModel) data.model = model;
1849
+ return data;
1850
+ }
1522
1851
  var DNotifier = class {
1523
1852
  /** @type {typeof Agent} */
1524
1853
  static Agent = Agent;
@@ -1558,6 +1887,9 @@ var DNotifier = class {
1558
1887
  });
1559
1888
  this.onDisconnectedCallback = onDisconnected || (() => {
1560
1889
  });
1890
+ this._remoteAgentPending = /* @__PURE__ */ new Map();
1891
+ this._waitForMessageWaiters = [];
1892
+ this._workflowListeners = [];
1561
1893
  this.isConnected = false;
1562
1894
  this.aiEnabled = false;
1563
1895
  this.messageSizeLimit = 32 * 1024;
@@ -1642,7 +1974,8 @@ var DNotifier = class {
1642
1974
  try {
1643
1975
  const { metadata: metadata2, data } = chunk;
1644
1976
  const packet = metadata2?.packet ?? metadata2;
1645
- if (!handshakeDone && metadata2.packet.code === "102" && metadata2.packet.sender.includes(
1977
+ const packetCode = packet?.code != null ? String(packet.code) : "";
1978
+ if (!handshakeDone && packetCode === "102" && String(packet?.sender ?? "").includes(
1646
1979
  prefixId(this.appId, this.userId)
1647
1980
  )) {
1648
1981
  handshakeDone = true;
@@ -1656,7 +1989,7 @@ var DNotifier = class {
1656
1989
  const messageId = packet.id;
1657
1990
  let promptResponse = null;
1658
1991
  if (totalPackets === 1 || !messageId) {
1659
- if (packet.code == "300") {
1992
+ if (packetCode === "300") {
1660
1993
  try {
1661
1994
  promptResponse = new Payload(data).toJSON();
1662
1995
  this._logsClient.completeAiLogging({
@@ -1669,7 +2002,7 @@ var DNotifier = class {
1669
2002
  console.error("Session step completion failed:", err);
1670
2003
  }
1671
2004
  }
1672
- this.onMessageCallback({
2005
+ this._dispatchInboundMessage({
1673
2006
  metadata: {
1674
2007
  id: packet.id,
1675
2008
  type: packet.type ?? packet.sender,
@@ -1690,7 +2023,7 @@ var DNotifier = class {
1690
2023
  if (entry.chunks.some((c) => c === null)) return;
1691
2024
  const fullBuffer = mergeChunks(entry.chunks);
1692
2025
  messageBuffers.delete(messageId);
1693
- if (packet.code === 300) {
2026
+ if (packetCode === "300") {
1694
2027
  promptResponse = new Payload(fullBuffer).toJSON();
1695
2028
  this._logsClient.completeAiLogging({
1696
2029
  sessionId: messageId,
@@ -1699,7 +2032,7 @@ var DNotifier = class {
1699
2032
  console.error("Session step completion failed:", err);
1700
2033
  });
1701
2034
  }
1702
- this.onMessageCallback({
2035
+ this._dispatchInboundMessage({
1703
2036
  metadata: {
1704
2037
  id: packet.id,
1705
2038
  type: packet.type ?? packet.sender,
@@ -1729,8 +2062,140 @@ var DNotifier = class {
1729
2062
  reason: err?.message || "Transport error"
1730
2063
  });
1731
2064
  });
2065
+ return true;
2066
+ }
2067
+ }
2068
+ /**
2069
+ * @internal Route inbound WS messages: remote-agent protocol, waitForMessage, then user onMessage.
2070
+ * @param {{ metadata: object, payload: * }} msg
2071
+ */
2072
+ _dispatchInboundMessage(msg) {
2073
+ let data = null;
2074
+ try {
2075
+ data = msg?.payload?.toJSON?.() ?? null;
2076
+ } catch {
2077
+ data = null;
2078
+ }
2079
+ if (isRemoteAgentEnvelope(data) && isRemoteAgentReply(data)) {
2080
+ const pending = this._remoteAgentPending.get(data.correlationId);
2081
+ if (pending) {
2082
+ clearTimeout(pending.timer);
2083
+ this._remoteAgentPending.delete(data.correlationId);
2084
+ if (data.op === REMOTE_AGENT_OP.ERROR) {
2085
+ pending.reject(
2086
+ new WorkflowError(
2087
+ data.error?.message ?? "Remote agent failed",
2088
+ { agentName: pending.agentName }
2089
+ )
2090
+ );
2091
+ } else {
2092
+ pending.resolve({
2093
+ output: data.output,
2094
+ state: data.state && typeof data.state === "object" ? data.state : null
2095
+ });
2096
+ }
2097
+ return;
2098
+ }
2099
+ }
2100
+ if (isRemoteAgentEnvelope(data) && data.op === REMOTE_AGENT_OP.INVOKE) {
2101
+ const workflow = this._workflowListeners.find(
2102
+ (wf) => wf.hasLocalAgent(data.agentName)
2103
+ );
2104
+ if (workflow) {
2105
+ Promise.resolve().then(() => workflow._handleRemoteInvoke(this, msg, data)).catch((err) => {
2106
+ console.error("Remote agent invoke failed:", err);
2107
+ });
2108
+ return;
2109
+ }
2110
+ const replyTo = typeof data.replyTo === "string" && data.replyTo.trim() || bareUserId(this.appId, msg?.metadata?.sender);
2111
+ if (data.correlationId && replyTo) {
2112
+ sendRemoteAgentError(this, {
2113
+ senderId: this.userId,
2114
+ receiverId: replyTo,
2115
+ correlationId: data.correlationId,
2116
+ message: `Agent not hosted: ${data.agentName}`
2117
+ }).catch((err) => {
2118
+ console.error("Remote agent error reply failed:", err);
2119
+ });
2120
+ }
2121
+ return;
2122
+ }
2123
+ if (isRemoteAgentEnvelope(data)) {
2124
+ return;
2125
+ }
2126
+ if (this._waitForMessageWaiters.length > 0) {
2127
+ const waiter = this._waitForMessageWaiters.shift();
2128
+ clearTimeout(waiter.timer);
2129
+ waiter.resolve(msg);
2130
+ return;
2131
+ }
2132
+ this.onMessageCallback(msg);
2133
+ }
2134
+ /**
2135
+ * @internal
2136
+ * @param {string} correlationId
2137
+ * @param {{ timeoutMs?: number, agentName?: string }} [options]
2138
+ */
2139
+ _awaitRemoteAgentReply(correlationId2, options = {}) {
2140
+ const timeoutMs = options.timeoutMs != null ? options.timeoutMs : DEFAULT_TIMEOUT_MS;
2141
+ return new Promise((resolve, reject) => {
2142
+ const timer = setTimeout(() => {
2143
+ this._remoteAgentPending.delete(correlationId2);
2144
+ reject(
2145
+ new WorkflowError(
2146
+ `Remote agent timed out after ${timeoutMs}ms${options.agentName ? `: ${options.agentName}` : ""}`,
2147
+ { agentName: options.agentName }
2148
+ )
2149
+ );
2150
+ }, timeoutMs);
2151
+ this._remoteAgentPending.set(correlationId2, {
2152
+ resolve,
2153
+ reject,
2154
+ timer,
2155
+ agentName: options.agentName
2156
+ });
2157
+ });
2158
+ }
2159
+ /**
2160
+ * @internal
2161
+ * @param {{ timeoutMs?: number }} [options]
2162
+ */
2163
+ _waitForInboundMessage(options = {}) {
2164
+ const timeoutMs = options.timeoutMs != null ? options.timeoutMs : DEFAULT_TIMEOUT_MS;
2165
+ const entry = { resolve: () => {
2166
+ }, reject: () => {
2167
+ }, timer: null };
2168
+ entry.timer = setTimeout(() => {
2169
+ const idx = this._waitForMessageWaiters.indexOf(entry);
2170
+ if (idx >= 0) this._waitForMessageWaiters.splice(idx, 1);
2171
+ entry.reject(
2172
+ new WorkflowError(`waitForMessage timed out after ${timeoutMs}ms`)
2173
+ );
2174
+ }, timeoutMs);
2175
+ return new Promise((resolve, reject) => {
2176
+ entry.resolve = resolve;
2177
+ entry.reject = reject;
2178
+ this._waitForMessageWaiters.push(entry);
2179
+ });
2180
+ }
2181
+ /**
2182
+ * @internal
2183
+ * @param {import("./workflow/workflow.js").Workflow} workflow
2184
+ */
2185
+ _registerWorkflowListener(workflow) {
2186
+ if (!this._workflowListeners.includes(workflow)) {
2187
+ this._workflowListeners.push(workflow);
1732
2188
  }
1733
2189
  }
2190
+ /**
2191
+ * @internal
2192
+ * @param {import("./workflow/workflow.js").Workflow} workflow
2193
+ */
2194
+ _unregisterWorkflowListener(workflow) {
2195
+ this._workflowListeners = this._workflowListeners.filter(
2196
+ (wf) => wf !== workflow
2197
+ );
2198
+ }
1734
2199
  /**
1735
2200
  * Returns the plan limits from the last successful authentication.
1736
2201
  * @returns {{ messagesHardLimit: number, maxRequestsPerMonth: number, maxAIWordsPerMonth: number, knowledgeBaseMaxWords: number, aiEnabled: boolean, maxUsers: number, maxRowsPerUser: number } | null}
@@ -1810,9 +2275,20 @@ var DNotifier = class {
1810
2275
  * @param {Object} options
1811
2276
  * @param {string} options.senderId - Sender user id.
1812
2277
  * @param {string | object} options.message - Message or payload to send to AI.
1813
- * @returns {string} - The message id.
2278
+ * @param {boolean} [options.saveHistory=true]
2279
+ * @param {string | null} [options.sessionId]
2280
+ * @param {string} [options.provider] - AI provider (e.g. `"open_ai"`). Merged into `data`.
2281
+ * @param {string} [options.model] - Model id (e.g. `"gpt-4o"`). Merged into `data`.
2282
+ * @returns {Promise<*>} - HTTP AI response, message id for WS, or null on error.
1814
2283
  */
1815
- async sendAI({ senderId, message, saveHistory = true, sessionId = null }) {
2284
+ async sendAI({
2285
+ senderId,
2286
+ message,
2287
+ saveHistory = true,
2288
+ sessionId = null,
2289
+ provider,
2290
+ model
2291
+ }) {
1816
2292
  try {
1817
2293
  if (!this.isConnected) throw new Error("Not connected");
1818
2294
  if (!senderId) throw new Error("senderId required");
@@ -1828,13 +2304,15 @@ var DNotifier = class {
1828
2304
  token: this.authToken,
1829
2305
  saveHistory
1830
2306
  };
2307
+ const data = buildAiSendData(message, { provider, model });
1831
2308
  await this._logsClient.startAiLogging({
1832
2309
  sessionId: _msgId,
1833
- prompts: message,
1834
- isExistingSession: Boolean(sessionId)
2310
+ prompts: data,
2311
+ isExistingSession: Boolean(sessionId),
2312
+ model: data?.model ?? model ?? null
1835
2313
  });
1836
2314
  if (this.transport instanceof HttpTransport) {
1837
- const response = await this.transport.send({ metadata, data: message });
2315
+ const response = await this.transport.send({ metadata, data });
1838
2316
  await this._logsClient.completeAiLogging({
1839
2317
  sessionId: _msgId,
1840
2318
  response
@@ -1842,7 +2320,7 @@ var DNotifier = class {
1842
2320
  return response;
1843
2321
  }
1844
2322
  if (this.transport instanceof WebsocketTransport) {
1845
- const payloadBuffer = toUint8(JSON.stringify(message));
2323
+ const payloadBuffer = toUint8(JSON.stringify(data));
1846
2324
  const frame = framePacket(metadata, payloadBuffer);
1847
2325
  this.transport.sendBinary(frame);
1848
2326
  }
@@ -2211,13 +2689,20 @@ var DNotifier = class {
2211
2689
  }
2212
2690
  /**
2213
2691
  * Resume a workflow context on a remote server (append-only observability).
2692
+ * Prefer `workflow.listen(notifier)` for hosting agents — that path uses
2693
+ * the host Workflow's registrations and `ctx.runAgent`.
2214
2694
  * @param {{
2215
2695
  * executionId: string,
2216
2696
  * workflowId: string,
2217
2697
  * parentStepId?: string | null,
2218
2698
  * }} traceCtx
2699
+ * @param {{
2700
+ * workflow?: import("./workflow/workflow.js").Workflow,
2701
+ * input?: *,
2702
+ * state?: object,
2703
+ * }} [options]
2219
2704
  */
2220
- async resumeWorkflowContext(traceCtx) {
2705
+ async resumeWorkflowContext(traceCtx, options = {}) {
2221
2706
  if (!traceCtx?.executionId || !traceCtx?.workflowId) {
2222
2707
  throw new Error("traceCtx requires executionId and workflowId");
2223
2708
  }
@@ -2226,19 +2711,22 @@ var DNotifier = class {
2226
2711
  token: this.authToken ?? null,
2227
2712
  appendOnly: true
2228
2713
  });
2229
- const workflow = new Workflow({
2714
+ const workflow = options.workflow ?? new Workflow({
2230
2715
  name: traceCtx.workflowId,
2231
2716
  observability: true,
2232
2717
  entry: async () => {
2233
2718
  }
2234
2719
  });
2235
- await observability.registerWorkflow(workflow);
2720
+ if (workflow.observability) {
2721
+ await observability.registerWorkflow(workflow);
2722
+ }
2236
2723
  return new WorkflowContext({
2237
2724
  notifier: this,
2238
2725
  senderId: this.userId,
2239
2726
  workflow,
2240
- input: null,
2241
- observability,
2727
+ input: options.input ?? null,
2728
+ state: options.state && typeof options.state === "object" ? { ...options.state } : {},
2729
+ observability: workflow.observability ? observability : null,
2242
2730
  executionId: traceCtx.executionId,
2243
2731
  traceParentStepId: traceCtx.parentStepId ?? null
2244
2732
  });