@muxoai/platform 1.4.2 → 1.4.4

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 (40) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/README.md +15 -1
  4. package/dist/cli.js +217 -0
  5. package/dist/composio-catalog.d.ts +25 -0
  6. package/dist/composio-catalog.js +145 -0
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.js +1 -0
  9. package/dist/durable-workflow.d.ts +71 -4
  10. package/dist/durable-workflow.js +199 -5
  11. package/dist/engine.d.ts +110 -4
  12. package/dist/engine.js +603 -24
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.js +3 -0
  15. package/dist/mcp-schema.d.ts +14 -0
  16. package/dist/mcp-schema.js +85 -7
  17. package/dist/mcp.js +325 -5
  18. package/dist/memory-graph.d.ts +26 -2
  19. package/dist/memory-graph.js +127 -7
  20. package/dist/oss-suite.d.ts +401 -0
  21. package/dist/oss-suite.js +2065 -0
  22. package/dist/policy.js +59 -0
  23. package/dist/providers/composio-instant.js +54 -36
  24. package/dist/providers/composio-sdk.d.ts +10 -1
  25. package/dist/providers/composio-sdk.js +144 -31
  26. package/dist/sdk.d.ts +43 -1
  27. package/dist/sdk.js +85 -2
  28. package/dist/server.js +231 -3
  29. package/dist/skills-catalog.d.ts +66 -0
  30. package/dist/skills-catalog.js +801 -0
  31. package/dist/types.d.ts +51 -1
  32. package/dist/ui/console-html.js +23 -8
  33. package/dist/version.d.ts +1 -1
  34. package/dist/version.js +1 -1
  35. package/package.json +1 -1
  36. package/plugins/muxo/.claude-plugin/plugin.json +1 -1
  37. package/plugins/muxo/.codex-plugin/plugin.json +2 -2
  38. package/plugins/muxo/.cursor-plugin/plugin.json +1 -1
  39. package/plugins/muxo/plugin.json +2 -2
  40. package/plugins/muxo/skills/muxo/SKILL.md +13 -3
package/dist/engine.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import crypto from "node:crypto";
2
2
  import { isStripeProjectsExclusiveProvider, normalizeStripeProjectsProviderSlug, wrapMuxoConnectUrl, } from "./composio-catalog.js";
3
3
  import { APPROVED_PLAN_STATUSES, approvalRequiredError, buildApprovalHumanHandoff, buildApprovalUrl, buildOAuthHumanHandoff, clampWaitSeconds, looksLikeToolSlug, unknownToolError, } from "./mcp-schema.js";
4
- import { completeCloudProvisioningWorkflow, createCloudProvisioningWorkflow, normalizeWorkflowTarget, workflowNotFoundError, } from "./durable-workflow.js";
4
+ import { completeCloudProvisioningWorkflow, createCloudProvisioningWorkflow, exportTemporalEventHistory, normalizeWorkflowTarget, rollbackDurableWorkflow as runSagaRollbackOnWorkflow, signalDurableWorkflow as sendSignalToWorkflow, workflowNotFoundError, } from "./durable-workflow.js";
5
5
  import { buildMemoryKnowledgeGraph } from "./memory-graph.js";
6
+ import { MUXO_COMMERCIAL_PLAYBOOKS, buildApprovalImpactPreview, buildBusinessReceiptSummary, buildCommercialRoiReport, buildHarnessConfigurationBundle, buildOtelTraceExport, buildPlaybookSagaExecution, buildRunReconciliationReport, compileWorkspacePolicyToCedarAndRego, evaluateCedarAndOpaPolicy, getCommercialPlaybook, parseNaturalLanguageCustomPlaybook, parseNaturalLanguageOssIntent, resolveHarnessPreset, } from "./oss-suite.js";
6
7
  import { resolveNaturalLanguageIntent, } from "./nl.js";
7
8
  import { DEFAULT_WORKSPACE_POLICY, buildLlmPolicyAndGovernanceBrief, compileNaturalLanguageGuardrailWithLlm, describePolicyInPlainEnglish, formatHumanFriendlyExplanation, parseNaturalLanguageGuardrail, simulatePolicyEvaluation, } from "./policy.js";
8
9
  import { ComposioInstantAdapter } from "./providers/composio-instant.js";
@@ -39,6 +40,7 @@ export class MuxoEngine {
39
40
  governance;
40
41
  supermemory;
41
42
  durableWorkflows = new Map();
43
+ customPlaybooks = new Map();
42
44
  constructor(config, store) {
43
45
  this.config = config;
44
46
  this.store = store;
@@ -625,6 +627,19 @@ export class MuxoEngine {
625
627
  decisionRecord,
626
628
  memoryContext,
627
629
  });
630
+ plan.changePreview = buildApprovalImpactPreview({
631
+ toolSlug: plan.toolSlug,
632
+ lane: plan.lane,
633
+ riskLevel: plan.riskLevel,
634
+ input: plan.input,
635
+ reason: plan.reason,
636
+ creditCost: plan.creditCost,
637
+ fundingMode: byokActive ? "byok" : "muxo_funded",
638
+ supplierSettlement: plan.supplierSettlement,
639
+ decisionRecord: plan.decisionRecord,
640
+ workspaceName: ws.name,
641
+ });
642
+ plan.estimatedCostUsd = plan.changePreview.estimatedCostUsd;
628
643
  // 3. Check external user OAuth connection state for Connected Apps (composio_sdk)
629
644
  let authHandoff;
630
645
  if (tool.lane === "composio_sdk" && tool.requiresAuth) {
@@ -693,6 +708,21 @@ export class MuxoEngine {
693
708
  const plan = this.store.getPlan(ctx.workspace.id, planId);
694
709
  if (!plan)
695
710
  throw new Error(`Plan '${planId}' not found in workspace.`);
711
+ if (!plan.changePreview) {
712
+ const ws = this.store.getWorkspace(ctx.workspace.id);
713
+ plan.changePreview = buildApprovalImpactPreview({
714
+ toolSlug: plan.toolSlug,
715
+ lane: plan.lane,
716
+ riskLevel: plan.riskLevel,
717
+ input: plan.input,
718
+ reason: plan.reason,
719
+ creditCost: plan.creditCost,
720
+ supplierSettlement: plan.supplierSettlement,
721
+ decisionRecord: plan.decisionRecord,
722
+ workspaceName: ws?.name,
723
+ });
724
+ plan.estimatedCostUsd = plan.changePreview.estimatedCostUsd;
725
+ }
696
726
  return plan;
697
727
  }
698
728
  async waitForPlanApproval(ctx, params) {
@@ -1130,18 +1160,25 @@ export class MuxoEngine {
1130
1160
  }
1131
1161
  /**
1132
1162
  * Synthesizes a Bi-Temporal Knowledge Graph (entities, active relationships, superseded historical relationships,
1133
- * Mermaid diagram, and human + technical explanations) directly from SQLite temporal_facts, memories, resources, and connections.
1163
+ * Mermaid diagram, point-in-time `asOf` time-travel, 2-hop BFS subgraph, and human + technical explanations)
1164
+ * directly from SQLite temporal_facts, memories, resources, and connections.
1134
1165
  */
1135
- async getMemoryGraph(ctx, query) {
1166
+ async getMemoryGraph(ctx, queryOrOptions) {
1136
1167
  const ws = this.store.getWorkspace(ctx.workspace.id);
1137
- const overview = await this.getMemoryOverview(ctx, query);
1168
+ const opts = typeof queryOrOptions === "string"
1169
+ ? { query: queryOrOptions }
1170
+ : queryOrOptions || {};
1171
+ const overview = await this.getMemoryOverview(ctx, opts.query);
1138
1172
  return buildMemoryKnowledgeGraph({
1139
1173
  workspace: ws,
1140
1174
  namespace: overview.namespace,
1141
- query,
1175
+ query: opts.query,
1176
+ asOf: opts.asOf || null,
1177
+ focalEntity: opts.focalEntity || null,
1178
+ maxHops: opts.maxHops,
1142
1179
  facts: this.store.listTemporalFacts(ws.id, {
1143
1180
  includeHistorical: true,
1144
- query,
1181
+ query: opts.query,
1145
1182
  limit: 100,
1146
1183
  }),
1147
1184
  resources: this.store.listResources(ws.id),
@@ -1194,6 +1231,13 @@ export class MuxoEngine {
1194
1231
  const existingRun = this.store.getRun(ctx.workspace.id, plan.runId);
1195
1232
  const existingReceipt = this.store.getReceipt(ctx.workspace.id, plan.runId);
1196
1233
  if (existingRun && existingReceipt) {
1234
+ existingRun.idempotentReplay = true;
1235
+ existingRun.reconciliationStatus =
1236
+ existingRun.status === "succeeded"
1237
+ ? "verified_complete"
1238
+ : existingRun.status === "cancelled"
1239
+ ? "cancelled"
1240
+ : "failed_zero_charge";
1197
1241
  return { run: existingRun, receipt: existingReceipt };
1198
1242
  }
1199
1243
  throw new Error(`Plan '${plan.id}' was already claimed by run '${plan.runId}' (execute-once invariant).`);
@@ -1365,6 +1409,24 @@ export class MuxoEngine {
1365
1409
  run: finalized.run,
1366
1410
  workspace: ws,
1367
1411
  });
1412
+ finalized.receipt.businessSummary = buildBusinessReceiptSummary({
1413
+ toolSlug: finalized.receipt.toolSlug,
1414
+ lane: finalized.receipt.lane,
1415
+ riskLevel: finalized.receipt.riskLevel,
1416
+ status: finalized.receipt.status,
1417
+ creditsMetered: finalized.receipt.creditsMetered,
1418
+ input: plan.input,
1419
+ output,
1420
+ approvedBy: plan.approvedBy,
1421
+ actorId: finalized.receipt.actorId,
1422
+ decisionRecord: finalized.receipt.decisionRecord,
1423
+ supplierSettlement: finalized.receipt.supplierSettlement,
1424
+ });
1425
+ finalized.receipt.estimatedCostUsd =
1426
+ finalized.receipt.businessSummary.costUsd;
1427
+ finalized.run.estimatedCostUsd =
1428
+ finalized.receipt.businessSummary.costUsd;
1429
+ finalized.run.reconciliationStatus = "verified_complete";
1368
1430
  finalized.receipt.explanation = this.explainReceipt(finalized.receipt, {
1369
1431
  signatureValid: this.store.verifyReceipt(finalized.receipt),
1370
1432
  governanceSignatureValid: true,
@@ -1444,6 +1506,25 @@ export class MuxoEngine {
1444
1506
  run: failedFinalized.run,
1445
1507
  workspace: ws,
1446
1508
  });
1509
+ failedFinalized.receipt.businessSummary = buildBusinessReceiptSummary({
1510
+ toolSlug: failedFinalized.receipt.toolSlug,
1511
+ lane: failedFinalized.receipt.lane,
1512
+ riskLevel: failedFinalized.receipt.riskLevel,
1513
+ status: failedFinalized.receipt.status,
1514
+ creditsMetered: failedFinalized.receipt.creditsMetered,
1515
+ input: plan.input,
1516
+ output: { error: errorMessage },
1517
+ error: errorMessage,
1518
+ approvedBy: plan.approvedBy,
1519
+ actorId: failedFinalized.receipt.actorId,
1520
+ decisionRecord: failedFinalized.receipt.decisionRecord,
1521
+ supplierSettlement: failedFinalized.receipt.supplierSettlement,
1522
+ });
1523
+ failedFinalized.receipt.estimatedCostUsd =
1524
+ failedFinalized.receipt.businessSummary.costUsd;
1525
+ failedFinalized.run.estimatedCostUsd =
1526
+ failedFinalized.receipt.businessSummary.costUsd;
1527
+ failedFinalized.run.reconciliationStatus = "failed_zero_charge";
1447
1528
  failedFinalized.receipt.explanation = this.explainReceipt(failedFinalized.receipt, {
1448
1529
  signatureValid: this.store.verifyReceipt(failedFinalized.receipt),
1449
1530
  governanceSignatureValid: true,
@@ -1511,15 +1592,31 @@ export class MuxoEngine {
1511
1592
  const verified = verification.signatureValid &&
1512
1593
  verification.governanceSignatureValid &&
1513
1594
  agenticOk;
1595
+ const businessSummary = receipt.businessSummary ||
1596
+ buildBusinessReceiptSummary({
1597
+ toolSlug: receipt.toolSlug,
1598
+ lane: receipt.lane,
1599
+ riskLevel: receipt.riskLevel,
1600
+ status: receipt.status,
1601
+ creditsMetered: receipt.creditsMetered,
1602
+ decisionRecord: receipt.decisionRecord,
1603
+ supplierSettlement: receipt.supplierSettlement,
1604
+ actorId: receipt.actorId,
1605
+ });
1606
+ receipt.businessSummary = businessSummary;
1607
+ receipt.estimatedCostUsd = businessSummary.costUsd;
1514
1608
  const headline = receipt.status === "succeeded"
1515
- ? `Verified Receipt (${receipt.id}): ${receipt.toolSlug} succeeded and passed all safety & integrity checks.`
1609
+ ? `Verified Receipt (${receipt.id}): ${receipt.toolSlug} succeeded · ${businessSummary.costDisplay}`
1516
1610
  : receipt.status === "failed"
1517
- ? `Verified Receipt (${receipt.id}): ${receipt.toolSlug} failed (0 credits charged).`
1611
+ ? `Verified Receipt (${receipt.id}): ${receipt.toolSlug} failed (0 credits charged / $0.00 USD).`
1518
1612
  : `Verified Receipt (${receipt.id}): ${receipt.toolSlug} was cancelled.`;
1519
1613
  const nonTechnical = [
1520
1614
  headline,
1521
- `Action: ${receipt.toolSlug} (${receipt.riskLevel} risk lane) at ${receipt.issuedAt}.`,
1522
- `Cost & billing: ${fundingPlain}.`,
1615
+ `What changed: ${businessSummary.whatChanged}`,
1616
+ `Who authorized it: ${businessSummary.whoAuthorized}.`,
1617
+ `What succeeded: ${businessSummary.whatSucceeded}`,
1618
+ `What remains unresolved: ${businessSummary.whatRemainsUnresolved}`,
1619
+ `Cost & billing: ${businessSummary.costDisplay}.`,
1523
1620
  verified
1524
1621
  ? "Tamper-proof check: Verified (HMAC vault signature, portable Ed25519 AgenticReceipt envelope, and governance audit trail all match)."
1525
1622
  : "Tamper-proof check: Warning (signature verification mismatch detected).",
@@ -1544,12 +1641,30 @@ export class MuxoEngine {
1544
1641
  throw new Error(`Receipt '${receiptOrRunId}' not found in workspace.`);
1545
1642
  }
1546
1643
  const run = this.store.getRun(ws.id, receipt.runId);
1644
+ const plan = run ? this.store.getPlan(ws.id, run.planId) : undefined;
1547
1645
  const agenticReceipt = this.governance.buildPortableAgenticReceipt({
1548
1646
  receipt,
1549
1647
  run,
1550
1648
  workspace: ws,
1551
1649
  });
1552
1650
  receipt.agenticReceipt = agenticReceipt;
1651
+ if (!receipt.businessSummary) {
1652
+ receipt.businessSummary = buildBusinessReceiptSummary({
1653
+ toolSlug: receipt.toolSlug,
1654
+ lane: receipt.lane,
1655
+ riskLevel: receipt.riskLevel,
1656
+ status: receipt.status,
1657
+ creditsMetered: receipt.creditsMetered,
1658
+ input: run?.input,
1659
+ output: run?.output,
1660
+ error: run?.error,
1661
+ approvedBy: plan?.approvedBy,
1662
+ actorId: receipt.actorId,
1663
+ decisionRecord: receipt.decisionRecord,
1664
+ supplierSettlement: receipt.supplierSettlement,
1665
+ });
1666
+ }
1667
+ receipt.estimatedCostUsd = receipt.businessSummary.costUsd;
1553
1668
  const signatureValid = this.store.verifyReceipt(receipt);
1554
1669
  const governanceSignatureValid = receipt.decisionRecord
1555
1670
  ? this.governance.verifyDecisionRecord(receipt.decisionRecord)
@@ -1564,19 +1679,84 @@ export class MuxoEngine {
1564
1679
  governanceSignatureValid,
1565
1680
  agenticReceiptValid,
1566
1681
  explanation,
1682
+ businessSummary: receipt.businessSummary,
1567
1683
  };
1568
1684
  }
1685
+ reconcileRun(ctx, runOrPlanId) {
1686
+ const ws = this.store.getWorkspace(ctx.workspace.id);
1687
+ const trimmed = String(runOrPlanId || "").trim();
1688
+ const directRun = trimmed === "latest" || trimmed === "last" || !trimmed
1689
+ ? this.store.listRuns(ws.id, 1)[0]
1690
+ : this.store.getRun(ws.id, trimmed);
1691
+ const directPlan = !directRun ? this.store.getPlan(ws.id, trimmed) : undefined;
1692
+ const plan = directPlan ||
1693
+ (directRun ? this.store.getPlan(ws.id, directRun.planId) : undefined) ||
1694
+ null;
1695
+ const run = directRun ||
1696
+ (plan?.runId ? this.store.getRun(ws.id, plan.runId) : undefined) ||
1697
+ null;
1698
+ if (!run && !plan) {
1699
+ throw new Error(`No run or plan '${runOrPlanId}' found in workspace '${ws.slug}' for reconciliation.`);
1700
+ }
1701
+ const receipt = run ? this.store.getReceipt(ws.id, run.id) || null : null;
1702
+ if (receipt && !receipt.businessSummary) {
1703
+ receipt.businessSummary = buildBusinessReceiptSummary({
1704
+ toolSlug: receipt.toolSlug,
1705
+ lane: receipt.lane,
1706
+ riskLevel: receipt.riskLevel,
1707
+ status: receipt.status,
1708
+ creditsMetered: receipt.creditsMetered,
1709
+ input: run?.input,
1710
+ output: run?.output,
1711
+ error: run?.error,
1712
+ approvedBy: plan?.approvedBy,
1713
+ actorId: receipt.actorId,
1714
+ decisionRecord: receipt.decisionRecord,
1715
+ supplierSettlement: receipt.supplierSettlement,
1716
+ });
1717
+ receipt.estimatedCostUsd = receipt.businessSummary.costUsd;
1718
+ }
1719
+ const signatureValid = receipt ? this.store.verifyReceipt(receipt) : false;
1720
+ const report = buildRunReconciliationReport({
1721
+ run,
1722
+ plan,
1723
+ receipt,
1724
+ signatureValid,
1725
+ });
1726
+ if (run) {
1727
+ run.reconciliationStatus = report.reconciliationStatus;
1728
+ }
1729
+ return report;
1730
+ }
1569
1731
  listReceipts(ctx, limit = 25) {
1570
1732
  const ws = this.store.getWorkspace(ctx.workspace.id);
1571
1733
  const rows = this.store.listReceipts(ws.id, limit);
1572
1734
  const enriched = rows.map((r) => {
1573
1735
  const run = this.store.getRun(ws.id, r.runId);
1736
+ const plan = run ? this.store.getPlan(ws.id, run.planId) : undefined;
1574
1737
  const agenticReceipt = this.governance.buildPortableAgenticReceipt({
1575
1738
  receipt: r,
1576
1739
  run,
1577
1740
  workspace: ws,
1578
1741
  });
1579
1742
  r.agenticReceipt = agenticReceipt;
1743
+ if (!r.businessSummary) {
1744
+ r.businessSummary = buildBusinessReceiptSummary({
1745
+ toolSlug: r.toolSlug,
1746
+ lane: r.lane,
1747
+ riskLevel: r.riskLevel,
1748
+ status: r.status,
1749
+ creditsMetered: r.creditsMetered,
1750
+ input: run?.input,
1751
+ output: run?.output,
1752
+ error: run?.error,
1753
+ approvedBy: plan?.approvedBy,
1754
+ actorId: r.actorId,
1755
+ decisionRecord: r.decisionRecord,
1756
+ supplierSettlement: r.supplierSettlement,
1757
+ });
1758
+ }
1759
+ r.estimatedCostUsd = r.businessSummary.costUsd;
1580
1760
  const signatureValid = this.store.verifyReceipt(r);
1581
1761
  const governanceSignatureValid = r.decisionRecord
1582
1762
  ? this.governance.verifyDecisionRecord(r.decisionRecord)
@@ -2114,20 +2294,218 @@ export class MuxoEngine {
2114
2294
  humanMessage: memoryCheck.humanSummary,
2115
2295
  };
2116
2296
  }
2117
- // 2c-graph. Check if the user is asking for the bi-temporal knowledge graph / fact lineage ("Show my memory graph", "What is our knowledge graph?", "Show fact lineage")
2118
- if (/\b(?:memory\s+graph|knowledge\s+graph|temporal\s+graph|fact\s+lineage|bi[-\s]?temporal\s+(?:graph|lineage|facts))\b/i.test(cleanedPrompt)) {
2119
- const memoryGraph = await this.getMemoryGraph(ctx);
2120
- const synthResolution = makeControlPlaneResolution("workspace.memory.graph", rawPrompt, memoryGraph.explanation.preferred);
2121
- return {
2122
- ok: true,
2123
- executed: true,
2124
- status: "memory_graph",
2125
- intent: synthResolution,
2126
- resolution: synthResolution,
2127
- memoryGraph,
2128
- explanation: memoryGraph.explanation,
2129
- humanMessage: memoryGraph.explanation.preferred,
2130
- };
2297
+ // 2c-oss. Check if the user is invoking an OSS or Commercial Control-Plane capability in plain English
2298
+ const ossIntent = parseNaturalLanguageOssIntent(rawPrompt, {
2299
+ customPlaybooks: this.customPlaybooks.get(ws.id) || [],
2300
+ explicitInput: params.input,
2301
+ });
2302
+ if (ossIntent.matched && ossIntent.kind) {
2303
+ if (ossIntent.kind === "list_playbooks") {
2304
+ const playbooks = this.listCommercialPlaybooks(ctx);
2305
+ const humanMessage = `Available Saga Playbooks (${playbooks.length}): ${playbooks
2306
+ .map((p) => `${p.slug} (${p.name}, ~${p.estimatedMinutesSaved}m saved)`)
2307
+ .join("; ")}.`;
2308
+ const synthResolution = makeControlPlaneResolution("workspace.playbooks.list", rawPrompt, humanMessage);
2309
+ return {
2310
+ ok: true,
2311
+ executed: true,
2312
+ status: "playbook_listed",
2313
+ intent: synthResolution,
2314
+ resolution: synthResolution,
2315
+ playbooks,
2316
+ humanMessage,
2317
+ };
2318
+ }
2319
+ if (ossIntent.kind === "create_playbook" && ossIntent.customPlaybook) {
2320
+ const created = this.createCustomPlaybook(ctx, {
2321
+ prompt: rawPrompt,
2322
+ input: params.input,
2323
+ });
2324
+ const synthResolution = makeControlPlaneResolution("workspace.playbooks.create", rawPrompt, created.humanMessage, { slug: created.playbook.slug });
2325
+ return {
2326
+ ok: true,
2327
+ executed: true,
2328
+ status: "playbook_created",
2329
+ intent: synthResolution,
2330
+ resolution: synthResolution,
2331
+ playbook: created.playbook,
2332
+ playbooks: created.playbooks,
2333
+ humanMessage: created.humanMessage,
2334
+ };
2335
+ }
2336
+ if (ossIntent.kind === "run_playbook" && ossIntent.playbookSlug) {
2337
+ const ran = this.runCommercialPlaybook(ctx, {
2338
+ slug: ossIntent.playbookSlug,
2339
+ input: ossIntent.playbookInput || params.input,
2340
+ });
2341
+ const humanMessage = `Executed Saga playbook '${ran.playbook.name}' (${ran.playbook.slug}) as workflow ${ran.workflow.id} (${ran.workflow.steps.length} steps completed, ${ran.workflow.compensations?.length || 0} compensations registered).`;
2342
+ const synthResolution = makeControlPlaneResolution(`playbook.${ran.playbook.slug}`, rawPrompt, humanMessage, ossIntent.playbookInput || {});
2343
+ return {
2344
+ ok: true,
2345
+ executed: true,
2346
+ status: "playbook_executed",
2347
+ intent: synthResolution,
2348
+ resolution: synthResolution,
2349
+ playbook: ran.playbook,
2350
+ workflow: ran.workflow,
2351
+ humanMessage,
2352
+ };
2353
+ }
2354
+ if (ossIntent.kind === "rollback_workflow") {
2355
+ const rolledBack = this.rollbackDurableWorkflow(ctx, ossIntent.workflowId || "latest", { reason: ossIntent.workflowReason });
2356
+ const humanMessage = `Rolled back workflow ${rolledBack.id} (${rolledBack.compensations?.length || 0} LIFO Saga compensations executed). Reason: ${rolledBack.rollbackReason}.`;
2357
+ const synthResolution = makeControlPlaneResolution("workspace.workflow.rollback", rawPrompt, humanMessage, { workflowId: rolledBack.id, reason: rolledBack.rollbackReason });
2358
+ return {
2359
+ ok: true,
2360
+ executed: true,
2361
+ status: "workflow_rolled_back",
2362
+ intent: synthResolution,
2363
+ resolution: synthResolution,
2364
+ workflow: rolledBack,
2365
+ humanMessage,
2366
+ };
2367
+ }
2368
+ if (ossIntent.kind === "signal_workflow") {
2369
+ const signaled = this.signalDurableWorkflow(ctx, ossIntent.workflowId || "latest", {
2370
+ signalName: ossIntent.signalName || "human.approval.granted",
2371
+ payload: ossIntent.signalPayload,
2372
+ });
2373
+ const humanMessage = `Delivered Temporal signal '${ossIntent.signalName || "human.approval.granted"}' to workflow ${signaled.id} (status: ${signaled.status}).`;
2374
+ const synthResolution = makeControlPlaneResolution("workspace.workflow.signal", rawPrompt, humanMessage, {
2375
+ workflowId: signaled.id,
2376
+ signalName: ossIntent.signalName || "human.approval.granted",
2377
+ });
2378
+ return {
2379
+ ok: true,
2380
+ executed: true,
2381
+ status: "workflow_signaled",
2382
+ intent: synthResolution,
2383
+ resolution: synthResolution,
2384
+ workflow: signaled,
2385
+ humanMessage,
2386
+ };
2387
+ }
2388
+ if (ossIntent.kind === "workflow_history") {
2389
+ const wf = this.getDurableWorkflow(ctx, ossIntent.workflowId || "latest");
2390
+ const workflowHistory = exportTemporalEventHistory(wf);
2391
+ const humanMessage = `Temporal EventHistory for workflow ${wf.id} (status=${wf.status}, ${workflowHistory.events.length} events).`;
2392
+ const synthResolution = makeControlPlaneResolution("workspace.workflow.history", rawPrompt, humanMessage, { workflowId: wf.id });
2393
+ return {
2394
+ ok: true,
2395
+ executed: true,
2396
+ status: "workflow_history",
2397
+ intent: synthResolution,
2398
+ resolution: synthResolution,
2399
+ workflow: wf,
2400
+ workflowHistory,
2401
+ humanMessage,
2402
+ };
2403
+ }
2404
+ if (ossIntent.kind === "cedar_compile") {
2405
+ const cedarBundle = this.getPolicyAsCodeBundle(ctx);
2406
+ const synthResolution = makeControlPlaneResolution("workspace.governance.cedar_compile", rawPrompt, cedarBundle.explanation.preferred);
2407
+ return {
2408
+ ok: true,
2409
+ executed: true,
2410
+ status: "cedar_compiled",
2411
+ intent: synthResolution,
2412
+ resolution: synthResolution,
2413
+ cedarBundle,
2414
+ explanation: cedarBundle.explanation,
2415
+ humanMessage: cedarBundle.explanation.preferred,
2416
+ };
2417
+ }
2418
+ if (ossIntent.kind === "cedar_evaluate") {
2419
+ const cedarEvaluation = await this.evaluatePolicyAsCode(ctx, {
2420
+ toolSlug: ossIntent.toolSlug || "resource.turso.database",
2421
+ input: ossIntent.evaluationInput || params.input || {},
2422
+ });
2423
+ const humanMessage = `Cedar 4.0 & OPA Rego evaluation for '${cedarEvaluation.toolSlug}': ${cedarEvaluation.decision} (${cedarEvaluation.remediationForLlm}).`;
2424
+ const synthResolution = makeControlPlaneResolution("workspace.governance.cedar_evaluate", rawPrompt, humanMessage, {
2425
+ toolSlug: cedarEvaluation.toolSlug,
2426
+ decision: cedarEvaluation.decision,
2427
+ });
2428
+ return {
2429
+ ok: true,
2430
+ executed: true,
2431
+ status: "cedar_evaluated",
2432
+ intent: synthResolution,
2433
+ resolution: synthResolution,
2434
+ cedarEvaluation,
2435
+ humanMessage,
2436
+ };
2437
+ }
2438
+ if (ossIntent.kind === "otel_traces") {
2439
+ const otelTraces = this.exportOtelTraces(ctx, ossIntent.limit || 25);
2440
+ const humanMessage = `Exported ${otelTraces.spansCount} OpenTelemetry GenAI 1.29.0 / MCP 2026-07-28 span(s) and ${otelTraces.langfuseBatch.length} Langfuse trace event(s) (traceparent: ${otelTraces.w3cTraceParent}).`;
2441
+ const synthResolution = makeControlPlaneResolution("workspace.telemetry.otlp", rawPrompt, humanMessage);
2442
+ return {
2443
+ ok: true,
2444
+ executed: true,
2445
+ status: "otel_exported",
2446
+ intent: synthResolution,
2447
+ resolution: synthResolution,
2448
+ otelTraces,
2449
+ humanMessage,
2450
+ };
2451
+ }
2452
+ if (ossIntent.kind === "roi_analytics") {
2453
+ const roiReport = this.getCommercialRoiReport(ctx);
2454
+ const synthResolution = makeControlPlaneResolution("workspace.analytics.roi", rawPrompt, roiReport.explanation.preferred);
2455
+ return {
2456
+ ok: true,
2457
+ executed: true,
2458
+ status: "roi_analyzed",
2459
+ intent: synthResolution,
2460
+ resolution: synthResolution,
2461
+ roiReport,
2462
+ explanation: roiReport.explanation,
2463
+ humanMessage: roiReport.explanation.preferred,
2464
+ };
2465
+ }
2466
+ if (ossIntent.kind === "configure_harness") {
2467
+ const harnessConfig = await this.configureHarness(ctx, {
2468
+ preset: ossIntent.preset?.slug,
2469
+ harness: ossIntent.targetHarness,
2470
+ prompt: ossIntent.extraGuardrailPrompt || undefined,
2471
+ });
2472
+ const synthResolution = makeControlPlaneResolution("workspace.harness.configure", rawPrompt, harnessConfig.humanMessage, {
2473
+ preset: harnessConfig.appliedPreset?.slug || "custom",
2474
+ harness: harnessConfig.targetHarness,
2475
+ });
2476
+ return {
2477
+ ok: true,
2478
+ executed: true,
2479
+ status: "harness_configured",
2480
+ intent: synthResolution,
2481
+ resolution: synthResolution,
2482
+ harnessConfig,
2483
+ explanation: harnessConfig.explanation,
2484
+ humanMessage: harnessConfig.humanMessage,
2485
+ };
2486
+ }
2487
+ if (ossIntent.kind === "memory_graph") {
2488
+ const memoryGraph = await this.getMemoryGraph(ctx, {
2489
+ asOf: ossIntent.asOf || null,
2490
+ focalEntity: ossIntent.focalEntity || null,
2491
+ maxHops: ossIntent.maxHops,
2492
+ });
2493
+ const synthResolution = makeControlPlaneResolution("workspace.memory.graph", rawPrompt, memoryGraph.explanation.preferred, {
2494
+ asOf: ossIntent.asOf || null,
2495
+ focalEntity: ossIntent.focalEntity || null,
2496
+ maxHops: ossIntent.maxHops,
2497
+ });
2498
+ return {
2499
+ ok: true,
2500
+ executed: true,
2501
+ status: "memory_graph",
2502
+ intent: synthResolution,
2503
+ resolution: synthResolution,
2504
+ memoryGraph,
2505
+ explanation: memoryGraph.explanation,
2506
+ humanMessage: memoryGraph.explanation.preferred,
2507
+ };
2508
+ }
2131
2509
  }
2132
2510
  // 2c. Check if the user is asking what Muxo remembers ("What do you remember?", "Show my saved memories", "What are our default settings in memory?")
2133
2511
  if (/^(?:what\s+do\s+you\s+remember|what\s+(?:are|is)\s+(?:my|our)\s+(?:saved\s+)?(?:memories|memory|defaults|preferences)|show\s+(?:my|our)\s+(?:saved\s+)?(?:memories|memory|defaults)|recall\s+(?:my|our|workspace)\s+memories|list\s+(?:my|our|workspace)\s+memories)\b/i.test(cleanedPrompt)) {
@@ -2473,6 +2851,207 @@ export class MuxoEngine {
2473
2851
  listDurableWorkflows(workspaceId) {
2474
2852
  return Array.from(this.durableWorkflows.values()).filter((w) => w.workspaceId === workspaceId);
2475
2853
  }
2854
+ getDurableWorkflow(ctx, workflowId) {
2855
+ const requested = String(workflowId || "").trim();
2856
+ if (requested.toLowerCase() === "latest" || requested.toLowerCase() === "last") {
2857
+ const list = this.listDurableWorkflows(ctx.workspace.id);
2858
+ const latest = list[list.length - 1];
2859
+ if (!latest) {
2860
+ throw workflowNotFoundError("latest");
2861
+ }
2862
+ return latest;
2863
+ }
2864
+ const wf = this.durableWorkflows.get(requested);
2865
+ if (!wf || wf.workspaceId !== ctx.workspace.id) {
2866
+ throw workflowNotFoundError(requested);
2867
+ }
2868
+ return wf;
2869
+ }
2870
+ getDurableWorkflowHistory(ctx, workflowId) {
2871
+ const wf = this.getDurableWorkflow(ctx, workflowId);
2872
+ return exportTemporalEventHistory(wf);
2873
+ }
2874
+ signalDurableWorkflow(ctx, workflowId, params) {
2875
+ const wf = this.getDurableWorkflow(ctx, workflowId);
2876
+ return sendSignalToWorkflow(wf, params);
2877
+ }
2878
+ rollbackDurableWorkflow(ctx, workflowId, params) {
2879
+ const wf = this.getDurableWorkflow(ctx, workflowId);
2880
+ return runSagaRollbackOnWorkflow(wf, params);
2881
+ }
2882
+ /**
2883
+ * AWS Cedar & Open Policy Agent (OPA / Rego) Policy-as-Code Compiler & Evaluator.
2884
+ */
2885
+ getPolicyAsCodeBundle(ctx) {
2886
+ const ws = this.store.getWorkspace(ctx.workspace.id);
2887
+ return compileWorkspacePolicyToCedarAndRego(ws.policy, ws);
2888
+ }
2889
+ async evaluatePolicyAsCode(ctx, params) {
2890
+ const ws = this.store.getWorkspace(ctx.workspace.id);
2891
+ let resolvedSlug = String(params.toolSlug || "instant.web.search").trim();
2892
+ let riskLevel = params.riskLevel;
2893
+ let creditCost = params.creditCost;
2894
+ let lane = params.lane;
2895
+ try {
2896
+ const tool = await this.inspectTool(resolvedSlug);
2897
+ resolvedSlug = tool.slug;
2898
+ if (!riskLevel)
2899
+ riskLevel = tool.riskLevel;
2900
+ if (typeof creditCost !== "number")
2901
+ creditCost = tool.creditCost;
2902
+ if (!lane)
2903
+ lane = tool.lane;
2904
+ }
2905
+ catch {
2906
+ // Fall back to slug prefix heuristics
2907
+ }
2908
+ return evaluateCedarAndOpaPolicy({
2909
+ policy: ws.policy,
2910
+ workspace: ws,
2911
+ toolSlug: resolvedSlug,
2912
+ input: params.input || {},
2913
+ riskLevel,
2914
+ creditCost,
2915
+ lane,
2916
+ });
2917
+ }
2918
+ /**
2919
+ * OpenTelemetry (OTel GenAI / MCP Semantic Conventions) & Langfuse Trace Exporter.
2920
+ */
2921
+ exportOtelTraces(ctx, limit = 25) {
2922
+ const ws = this.store.getWorkspace(ctx.workspace.id);
2923
+ const runs = this.store.listRuns(ws.id, limit);
2924
+ const receipts = this.store.listReceipts(ws.id, limit);
2925
+ const plans = this.store.listPlans(ws.id, limit);
2926
+ return buildOtelTraceExport({
2927
+ workspace: ws,
2928
+ runs,
2929
+ receipts,
2930
+ plans,
2931
+ });
2932
+ }
2933
+ /**
2934
+ * Turnkey & Custom Commercial Business Saga Playbooks.
2935
+ */
2936
+ listCommercialPlaybooks(ctx) {
2937
+ const custom = ctx ? this.customPlaybooks.get(ctx.workspace.id) || [] : [];
2938
+ return [...custom, ...MUXO_COMMERCIAL_PLAYBOOKS];
2939
+ }
2940
+ createCustomPlaybook(ctx, params) {
2941
+ const ws = this.store.getWorkspace(ctx.workspace.id);
2942
+ const pb = parseNaturalLanguageCustomPlaybook(params.prompt || String(params.input?.prompt || params.input?.name || ""), params.input);
2943
+ const existing = (this.customPlaybooks.get(ws.id) || []).filter((item) => item.slug !== pb.slug);
2944
+ const updatedList = [pb, ...existing];
2945
+ this.customPlaybooks.set(ws.id, updatedList);
2946
+ this.store.upsertTemporalFact({
2947
+ workspaceId: ws.id,
2948
+ subject: `workspace:${ws.slug}`,
2949
+ predicate: "REGISTERED_CUSTOM_PLAYBOOK",
2950
+ object: `playbook:${pb.slug}`,
2951
+ summary: `Registered custom ${pb.steps.length}-step Saga playbook '${pb.name}' (${pb.slug})`,
2952
+ confidence: 0.99,
2953
+ sourceKind: "preference",
2954
+ sourceReferenceId: `pb_${pb.slug}`,
2955
+ });
2956
+ return {
2957
+ ok: true,
2958
+ playbook: pb,
2959
+ playbooks: this.listCommercialPlaybooks(ctx),
2960
+ humanMessage: `Created custom ${pb.steps.length}-step Saga playbook '${pb.slug}' (${pb.steps.map((s) => s.toolSlug).join(" → ")}).`,
2961
+ };
2962
+ }
2963
+ runCommercialPlaybook(ctx, params) {
2964
+ const ws = this.store.getWorkspace(ctx.workspace.id);
2965
+ const custom = this.customPlaybooks.get(ws.id) || [];
2966
+ const playbook = getCommercialPlaybook(params.slug, custom);
2967
+ if (!playbook) {
2968
+ const err = new Error(`Unknown commercial playbook '${params.slug}'. Available playbooks: ${[...custom, ...MUXO_COMMERCIAL_PLAYBOOKS].map((p) => p.slug).join(", ")}`);
2969
+ err.statusCode = 404;
2970
+ err.code = "PLAYBOOK_NOT_FOUND";
2971
+ throw err;
2972
+ }
2973
+ const wfId = `wf_saga_${Date.now()}_${crypto.randomBytes(4).toString("hex")}`;
2974
+ const executed = buildPlaybookSagaExecution({
2975
+ id: wfId,
2976
+ workspaceId: ws.id,
2977
+ workspaceSlug: ws.slug,
2978
+ playbook,
2979
+ input: params.input || {},
2980
+ });
2981
+ this.durableWorkflows.set(wfId, executed.workflow);
2982
+ const savedFact = this.store.upsertTemporalFact({
2983
+ workspaceId: ws.id,
2984
+ subject: executed.temporalFact.subject,
2985
+ predicate: executed.temporalFact.predicate,
2986
+ object: executed.temporalFact.object,
2987
+ summary: executed.temporalFact.summary,
2988
+ confidence: 0.99,
2989
+ sourceKind: "execution_outcome",
2990
+ sourceReferenceId: executed.temporalFact.episodeId,
2991
+ });
2992
+ return {
2993
+ ok: true,
2994
+ playbook: executed.playbook,
2995
+ workflow: executed.workflow,
2996
+ temporalFact: savedFact,
2997
+ usableResult: executed.usableResult,
2998
+ };
2999
+ }
3000
+ /**
3001
+ * Turnkey Harness Preset & One-Shot Agent Configurator.
3002
+ */
3003
+ async configureHarness(ctx, params) {
3004
+ let ws = this.store.getWorkspace(ctx.workspace.id);
3005
+ const matchedPreset = resolveHarnessPreset(params?.preset || params?.prompt || null);
3006
+ if (matchedPreset) {
3007
+ ws = this.store.updateWorkspacePolicy(ws.id, matchedPreset.policyPatch);
3008
+ this.store.upsertTemporalFact({
3009
+ workspaceId: ws.id,
3010
+ subject: `workspace:${ws.slug}`,
3011
+ predicate: "CONFIGURED_HARNESS_PRESET",
3012
+ object: `preset:${matchedPreset.slug}`,
3013
+ summary: `Applied harness preset '${matchedPreset.name}' (${matchedPreset.slug})`,
3014
+ confidence: 1.0,
3015
+ sourceKind: "policy_decision",
3016
+ sourceReferenceId: `preset_${matchedPreset.slug}`,
3017
+ });
3018
+ }
3019
+ if (params?.prompt) {
3020
+ const guardrailCheck = parseNaturalLanguageGuardrail(params.prompt, ws.policy);
3021
+ if (guardrailCheck.isGuardrail) {
3022
+ const applied = await this.applyNaturalLanguageGuardrail(ctx, params.prompt);
3023
+ ws = applied.workspace;
3024
+ }
3025
+ }
3026
+ return buildHarnessConfigurationBundle({
3027
+ workspace: ws,
3028
+ baseUrl: this.config.baseUrl,
3029
+ targetHarness: params?.harness || "all",
3030
+ appliedPreset: matchedPreset,
3031
+ });
3032
+ }
3033
+ /**
3034
+ * FinOps & Commercial ROI Unit-Economics Analytics.
3035
+ */
3036
+ getCommercialRoiReport(ctx) {
3037
+ const ws = this.store.getWorkspace(ctx.workspace.id);
3038
+ const runs = this.store.listRuns(ws.id, 100);
3039
+ const plans = this.store.listPlans(ws.id, 100);
3040
+ const resources = this.store.listResources(ws.id);
3041
+ const byokKeys = this.store.listByokKeys(ws.id);
3042
+ const temporalFacts = this.store.listTemporalFacts(ws.id, {
3043
+ includeHistorical: false,
3044
+ limit: 100,
3045
+ });
3046
+ return buildCommercialRoiReport({
3047
+ workspace: ws,
3048
+ runs,
3049
+ plans,
3050
+ resources,
3051
+ byokKeys,
3052
+ temporalFacts,
3053
+ });
3054
+ }
2476
3055
  /**
2477
3056
  * Hybrid Semantic Vector + Bi-Temporal Recall (`@cf/baai/bge-base-en-v1.5` + Vectorize model).
2478
3057
  */